How can I retrieve the first word of the output of a command in Bash?

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

echo "word1 word2" | ....

What should I put after the pipe?


Solution 1:

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.

Solution 2:

There isn't any need to use external commands. Bash itself can do the job. Assuming "word1 word2" you got from somewhere and stored in a variable, for example,

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

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

Solution 3:

I think one efficient way is the use of Bash arrays:

array=( $string ) # Do not use quotes in order to allow word expansion
echo ${array[0]}  # You can retrieve any word. Index runs from 0 to length-1

Also, you can directly read arrays in a pipe-line:

echo "word1 word2" | while read -a array; do echo "${array[0]}" ; done

Solution 4:

echo "word1 word2 word3" | { read first rest ; echo $first ; }

This has the advantage that is not using external commands and leaves the $1, $2, etc. variables intact.