How to retrieve the first word of the output of a command in bash?

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.


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.


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

Tags:

Bash