tags:

views:

40

answers:

4

I have a command, for example: echo "word1 word2". I want to put a pipe (|) and get word1 from the command.

echo "word1 word2" | ....

I don't know what to put after the pipe...

Thanks in advance

A: 
echo "word1 word2" | cut -f 1 -d " "

cut cuts the 1st field (-f 1) from a list of fields delimited by the string " " (-d " ")

lajuette
that's one way, but your cut statement won't distinguish multiple spaces in between words if he wants to get word2 later on
ghostdog74
+1  A: 

You could try awk

echo "word1 word2" | awk '{ print $1 }'

With awk it is really easy to pick any word you like ($1, $2, ...)

mfloryan
+1  A: 

Awk is a good option if you have to deal with trailing whitespace because it'll take care of it for you:

echo " word1 word2 " | awk '{print $1;}' // Prints "word1"

Cut won't take care of this though:

echo " word1 word2 " | cut -f 1 -d " " // Prints nothing/whitespace

'cut' here prints nothing/whitespace, because the first thing before a space was another space.

mattbh
A: 

no need to use external commands. Bash itself can do the job. Assuming "word1 word2" you got from somewhere and stored in a variable, eg

$ string="word1 word2"
$ set -- $string
$ echo $1
word1
$ echo $2
word2

now you can assign $1, or $2 etc to another variable if you like.

ghostdog74