searching a text string for n'th :

hello, i'm a novice on bsh scripting so thanks for any help here
basically i have a shell var $x that looks like this

> echo $x
nabc1234:!:73394:17155:Gary Mason:/home/garym:/bin/ksh

and i'm trying to keep the first 8 characters and the text from the 4th : to the 5th :

i've been trying to use the index function, but can figure out how to tell it the nth : to go to

echo `expr index "$x" $":"`   # returns 8

i know there are many ways to skin this cat.
but if you post a solution, please give me a little explaination/comments
thanks

echo $x | cut -d: -f1,5

To know how this command works, consult "man cut"

1 Like
y=${x%:*:*}
echo "${y%%:*} ${y##*:}"

here's my command string, the problem is when i get multiple lines from the passwd file. this only returns the first line's info, the result of the grep seems to put just one space between the lines and the cut thinks that it's looking at one line not 2. i've looked and man grep and man cut to see if there are any switches I should turn on and nothing has worked thus far.
any suggestions to get the second line to echo?

echo \\n \\r `cat /etc/passwd | grep -E Sean` | cut -d: -f1,5

When you execute a command in back quotes or $() the output is stripped of new lines (by the shell). You don't need to cat the file, grep will read it when given the file name on the command line:

grep -E Sean /etc/passwd | cut -d: -f1,5
1 Like

I've got this as a function in my .profile, and with out the ` ticks the grep doesn't invoke.
Double quotes don't help either
thanks

nbk ()
{
echo \\n \\r grep -E $1 /etc/passwd | cut -d: -f1,5
}
 
 
tx8apbci210:/home/nas/nbk1hhk> nbk Sean
 
 grep -E Sean /etc/passwd
tx8apbci210:/home/nas/nbk1hhk>

The grep won't fire because it's in the echo which isn't needed. Try this:

nbk ()
{
grep -E $1 /etc/passwd | cut -d: -f1,5
}

thanks

For the sake of clarity, lest a newbie be unintentionally misled, when the shell expands the command substitution, it only removes trailing newlines (if there are any); all other newlines are left intact (though they may be treated as field separators if the default value of IFS is in effect and the command substitution is unquoted).

Regards,
Alister

1 Like

Absolutely correct -- my mistake.

Thanks.