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

Bash

Bash Problem Overview


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?

Bash Solutions


Solution 1 - 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.

Solution 2 - Bash

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 - Bash

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 - Bash

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.

Solution 5 - Bash

Using shell parameter expansion %% *

Here is another solution using shell parameter expansion. It takes care of multiple spaces after the first word. Handling spaces in front of the first word requires one additional expansion.

string='word1    word2'
echo ${string%% *}
word1

string='word1    word2      '
echo ${string%% *}
word1
Explanation

The %% signifies deleting the longest possible match of ā€ƒ* (a space followed by any number of whatever other characters) in the trailing part of string.

Solution 6 - Bash

You could try AWK:

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

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

Solution 7 - Bash

If you are sure there are no leading spaces, you can use Bash parameter substitution:

$ string="word1  word2"
$ echo ${string/%\ */}
word1

Watch out for escaping the single space. See here for more examples of substitution patterns. If you have Bash > 3.0, you could also use regular expression matching to cope with leading spaces - see here:

$ string="  word1   word2"
$ [[ ${string} =~ \ *([^\ ]*) ]]
$ echo ${BASH_REMATCH[1]}
word1

Solution 8 - Bash

I wondered how several of the top answers measured up in terms of speed. I tested the following:

1 @mattbh's

echo "..." | awk '{print $1;}'

2 @ghostdog74's

string="..."; set -- $string; echo $1

3 @boontawee-home's

echo "..." | { read -a array ; echo ${array[0]} ; }

and 4 @boontawee-home's

echo "..." | { read first _ ; echo $first ; }

I measured them with Python's timeit in a Bash script in a zsh terminal on macOS, using a test string with 215 5-letter words. I did each measurement five times (the results were all for 100 loops, best of 3), and averaged the results:

Method       Time
--------------------------------
1. awk       9.2 ms
2. set       11.6 ms (1.26 * "1")
3. read -a   11.7 ms (1.27 * "1")
4. read      13.6 ms (1.48 * "1")

Solution 9 - Bash

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

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

Solution 10 - Bash

read is your friend:

  • If string is in a variable:

      string="word1 word2"
      read -r first _ <<< "$string"
      printf '%s\n' "$first"
    
  • If you're working in a pipe: first case: you only want the first word of the first line:

      printf '%s\n' "word1 word2" "line2" | { read -r first _; printf '%s\n' "$first"; }
    

second case: you want the first word of each line:

    printf '%s\n' "word1 word2" "worda wordb" | while read -r first _; do printf '%s\n' "$first"; done

These work if there are leading spaces:

printf '%s\n' "   word1 word2" | { read -r first _; printf '%s\n' "$first"; }

Solution 11 - Bash

As Perl incorporates AWK's functionality, this can be solved with Perl too:

echo " word1 word2" | perl -lane 'print $F[0]'

Solution 12 - Bash

I was working with an embedded device which had neither Perl, AWK or Python and did it with sed instead. It supports multiple spaces before the first word (which the cut and bash solutions did not handle).

VARIABLE="  first_word_with_spaces_before_and_after  another_word  "
echo $VARIABLE | sed 's/ *\([^ ]*\).*/\1/'

This was very useful when grepping ps for process IDs since the other solutions here using only Bash was not able to remove the first spaces which ps uses to align.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionNeuquinoView Question on Stackoverflow
Solution 1 - BashmattbhView Answer on Stackoverflow
Solution 2 - Bashghostdog74View Answer on Stackoverflow
Solution 3 - BashIsaíasView Answer on Stackoverflow
Solution 4 - BashJohn MarterView Answer on Stackoverflow
Solution 5 - BashSerge StroobandtView Answer on Stackoverflow
Solution 6 - BashmfloryanView Answer on Stackoverflow
Solution 7 - Bashdsl101View Answer on Stackoverflow
Solution 8 - BashhenryView Answer on Stackoverflow
Solution 9 - BashlajuetteView Answer on Stackoverflow
Solution 10 - Bashgniourf_gniourfView Answer on Stackoverflow
Solution 11 - BashtsschView Answer on Stackoverflow
Solution 12 - BashJohan BjäreholtView Answer on Stackoverflow