0

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?

choroba
  • 231,213
  • 25
  • 204
  • 289
richard008
  • 403
  • 7
  • 15

3 Answers3

3

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
William Pursell
  • 204,365
  • 48
  • 270
  • 300
1
grep "willybd" /dir/names | cut "-d " -f1-3

The default delimiter for cut is tab, not space.

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
DrC
  • 7,528
  • 1
  • 22
  • 37
0

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.

Adam Liss
  • 47,594
  • 12
  • 108
  • 150
  • Funny, I ran the commands you listed, and as I expected, it didn't print the original line. Are you sure you didn't `$echo $line`? Otherwise, I'm not sure why my one-line version would behave differently from yours. – Adam Liss Oct 04 '12 at 23:29