richard008
richard008

Reputation: 403

Unix/Linux Shell Grep to cut

I have a file, say 'names' that looks like this

first middle last     userid
Brian Duke Willy      willybd
...

whenever I use the following

line=`grep "willybd" /dir/names`
name=`echo $line | cut -f1-3 -d' '`
echo $name

It prints the following:

Brian Duke Willy      willybd
Brian Duke Willy

My question is, how would I get it to print just "Brian Duke Willy" without first printing the original line that I cut?

Upvotes: 0

Views: 2946

Answers (3)

DrC
DrC

Reputation: 7698

grep "willybd" /dir/names | cut "-d " -f1-3

The default delimiter for cut is tab, not space.

Upvotes: 1

William Pursell
William Pursell

Reputation: 212684

The usual way to do this sort of thing is:

awk '/willybd/{ print $1, $2, $3 }' /dir/names

or, to be more specific

awk '$4 ~ /willybd/ { print $1, $2, $3 }' /dir/names

or

awk '$4 == "willybd" { print $1, $2, $3 }' /dir/names

Upvotes: 3

Adam Liss
Adam Liss

Reputation: 48330

Unless you need the intermediate variables, you can use

grep "willybd" /dir/names | cut -f1-3 -d' '

One of the beautiful features of linux is that most commands can be used as filters: they read from stdin and write to stdout, which means you can "pipe" the output of one command into the next command. That's what the | character does. It's pronounced pipe.

Upvotes: 0

Related Questions