Facundo Ch.
Facundo Ch.

Reputation: 12214

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?

Upvotes: 164

Views: 212217

Answers (13)

Klas Mellbourn
Klas Mellbourn

Reputation: 44377

If you don't mind installing a new command, I would recommend choose

It has the simplest and most intuitive interface of all alternatives:

echo "word1 word2" | choose 0

Upvotes: 1

henry
henry

Reputation: 4385

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")

Upvotes: 14

Johan Bjäreholt
Johan Bjäreholt

Reputation: 780

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.

Upvotes: 0

tssch
tssch

Reputation: 764

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

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

Upvotes: 2

Isaías
Isaías

Reputation: 474

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

Upvotes: 38

dsl101
dsl101

Reputation: 1784

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

Upvotes: 16

ghostdog74
ghostdog74

Reputation: 342333

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.

Upvotes: 85

mfloryan
mfloryan

Reputation: 7685

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.).

Upvotes: 17

lajuette
lajuette

Reputation: 1017

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

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

Upvotes: 9

mattbh
mattbh

Reputation: 5485

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.

Upvotes: 248

Serge Stroobandt
Serge Stroobandt

Reputation: 31508

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.

Upvotes: 22

gniourf_gniourf
gniourf_gniourf

Reputation: 46823

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"; }

Upvotes: 6

John Marter
John Marter

Reputation: 721

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.

Upvotes: 36

Related Questions