How to 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" | ....
I don't know what to put after the pipe.
bash
add a comment |
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.
bash
add a comment |
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.
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" | ....
I don't know what to put after the pipe.
bash
bash
edited Oct 16 '16 at 16:31
user123456
197213
197213
asked Mar 13 '10 at 23:09
Neuquino
4,025134671
4,025134671
add a comment |
add a comment |
12 Answers
12
active
oldest
votes
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.
Is the semi-colon necessary?
– Alice Purcell
Jan 19 at 11:47
It should be "leading" whitespace (at the begin of the string), not "trailing".
– user202729
Oct 28 at 13:42
add a comment |
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.
5
Can you explain briefly how this works?
– Matt Montag
Mar 2 '14 at 2:37
6
+1 for using only shell built-ins andstdin
. @Matt M.--
meansstdin
, so$string
is being passed in asstdin
.stdin
is whitespace-separated into arguments$1
,$2
,$3
, etc. - just like when a Bash program evaluates arguments (e.g. check$1
,$2
, etc.), this approach takes advantage of the shell's tendency to split thestdin
into arguments automatically, removing the need forawk
orcut
.
– Caleb Xu
Apr 11 '14 at 1:38
3
@CalebXu Not stdin,set
sets the shell arguments.
– Guido
Nov 14 '14 at 14:54
8
word1=$(IFS=" " ; set -- $string ; echo $1)
Set IFS to correctly recognize the space between the words. Wrap in parentheses to avoid clobbering the original content of $1.
– Steve Pitchers
May 15 '15 at 10:27
This is broken as it's subject to pathname expansion. Try it withstring="*"
. Surprise.
– gniourf_gniourf
Mar 14 at 17:55
add a comment |
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
echo " word1 word2 " | { read -a array ; echo ${array[0]} ; }
– Boontawee Home
Feb 21 '16 at 16:44
This is broken as it's subject to pathname expansion. Try it withstring="*"
. Surprise.
– gniourf_gniourf
Mar 14 at 17:56
Use thewhile
syntax to retrieve every first word at each line. Otherwise, use Boontawee Home approach. Also, please note thatecho "${array[0]}"
has been quoted to prevent expansion as noticed by gniourf-gniourf.
– Isaías
Apr 9 at 23:28
If you try to access an index of array which is greater than the number of words, then you won't get an error. You will just get an empty line
– Dhumil Agarwal
May 22 at 6:40
add a comment |
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.
2
echo " word1 word2 " | { read first _ ; echo $first ; }
– Boontawee Home
Feb 21 '16 at 16:46
Leaving the variables$1, $2, …
intact is an extremely useful feature for script writing!
– Serge Stroobandt
Oct 21 '16 at 22:59
add a comment |
You could try awk
echo "word1 word2" | awk '{ print $1 }'
With awk it is really easy to pick any word you like ($1, $2, ...)
add a comment |
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
add a comment |
echo "word1 word2" | cut -f 1 -d " "
cut cuts the 1st field (-f 1) from a list of fields delimited by the string " " (-d " ")
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
Mar 14 '10 at 0:03
yep, the awk solution is the better one.
– lajuette
Mar 10 '14 at 9:29
add a comment |
Using shell paramter 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
Explanation
The %%
signifies deleting the longest match of *
(a space followed by whatever number of any other characters), starting from the right-hand side of the variable string
.
add a comment |
read
is your friend:
If string is in a variable:
string="word1 word2"
read -r first _ <<< "$string"
printf '%sn' "$first"
If you're working in a pipe: first case: you only want the first word of the first line:
printf '%sn' "word1 word2" "line2" | { read -r first _; printf '%sn' "$first"; }
second case: you want the first word of each line:
printf '%sn' "word1 word2" "worda wordb" | while read -r first _; do printf '%sn' "$first"; done
These work if there are leading spaces:
printf '%sn' " word1 word2" | { read -r first _; printf '%sn' "$first"; }
add a comment |
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. Did each measurement five times (the results were all for 100 loops, best of 3), and averaged the results:
method time
--------------------------------
1. awk 9.2ms
2. set 11.6ms (1.26 * "1")
3. read -a 11.7ms (1.27 * "1")
4. read 13.6ms (1.48 * "1")
Nice job, voters 👏 The votes (as of this writing) match the solutions' speed!
Weird that you could measure 3 in dash, since dash doesn't support arrays (read -a
is invalid in dash).
– gniourf_gniourf
Mar 14 at 17:58
Yeah that is weird. I ruled that one out, did the speed tests, then thought "why'd I leave that one out" and added it in. Removing it now, and I may rerun things later to make sure I didn't have some mistake
– henry
Mar 14 at 19:31
add a comment |
As perl incorporates awk's functionality this can be solved with perl too:
echo " word1 word2" | perl -lane 'print $F[0]'
add a comment |
I was working with a 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.
add a comment |
Your Answer
StackExchange.ifUsing("editor", function () {
StackExchange.using("externalEditor", function () {
StackExchange.using("snippets", function () {
StackExchange.snippets.init();
});
});
}, "code-snippets");
StackExchange.ready(function() {
var channelOptions = {
tags: "".split(" "),
id: "1"
};
initTagRenderer("".split(" "), "".split(" "), channelOptions);
StackExchange.using("externalEditor", function() {
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled) {
StackExchange.using("snippets", function() {
createEditor();
});
}
else {
createEditor();
}
});
function createEditor() {
StackExchange.prepareEditor({
heartbeatType: 'answer',
autoActivateHeartbeat: false,
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader: {
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
},
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
});
}
});
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f2440414%2fhow-to-retrieve-the-first-word-of-the-output-of-a-command-in-bash%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
12 Answers
12
active
oldest
votes
12 Answers
12
active
oldest
votes
active
oldest
votes
active
oldest
votes
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.
Is the semi-colon necessary?
– Alice Purcell
Jan 19 at 11:47
It should be "leading" whitespace (at the begin of the string), not "trailing".
– user202729
Oct 28 at 13:42
add a comment |
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.
Is the semi-colon necessary?
– Alice Purcell
Jan 19 at 11:47
It should be "leading" whitespace (at the begin of the string), not "trailing".
– user202729
Oct 28 at 13:42
add a comment |
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.
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.
edited Oct 26 '16 at 14:20
Nakilon
26.6k1283105
26.6k1283105
answered Mar 13 '10 at 23:37
mattbh
3,09022026
3,09022026
Is the semi-colon necessary?
– Alice Purcell
Jan 19 at 11:47
It should be "leading" whitespace (at the begin of the string), not "trailing".
– user202729
Oct 28 at 13:42
add a comment |
Is the semi-colon necessary?
– Alice Purcell
Jan 19 at 11:47
It should be "leading" whitespace (at the begin of the string), not "trailing".
– user202729
Oct 28 at 13:42
Is the semi-colon necessary?
– Alice Purcell
Jan 19 at 11:47
Is the semi-colon necessary?
– Alice Purcell
Jan 19 at 11:47
It should be "leading" whitespace (at the begin of the string), not "trailing".
– user202729
Oct 28 at 13:42
It should be "leading" whitespace (at the begin of the string), not "trailing".
– user202729
Oct 28 at 13:42
add a comment |
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.
5
Can you explain briefly how this works?
– Matt Montag
Mar 2 '14 at 2:37
6
+1 for using only shell built-ins andstdin
. @Matt M.--
meansstdin
, so$string
is being passed in asstdin
.stdin
is whitespace-separated into arguments$1
,$2
,$3
, etc. - just like when a Bash program evaluates arguments (e.g. check$1
,$2
, etc.), this approach takes advantage of the shell's tendency to split thestdin
into arguments automatically, removing the need forawk
orcut
.
– Caleb Xu
Apr 11 '14 at 1:38
3
@CalebXu Not stdin,set
sets the shell arguments.
– Guido
Nov 14 '14 at 14:54
8
word1=$(IFS=" " ; set -- $string ; echo $1)
Set IFS to correctly recognize the space between the words. Wrap in parentheses to avoid clobbering the original content of $1.
– Steve Pitchers
May 15 '15 at 10:27
This is broken as it's subject to pathname expansion. Try it withstring="*"
. Surprise.
– gniourf_gniourf
Mar 14 at 17:55
add a comment |
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.
5
Can you explain briefly how this works?
– Matt Montag
Mar 2 '14 at 2:37
6
+1 for using only shell built-ins andstdin
. @Matt M.--
meansstdin
, so$string
is being passed in asstdin
.stdin
is whitespace-separated into arguments$1
,$2
,$3
, etc. - just like when a Bash program evaluates arguments (e.g. check$1
,$2
, etc.), this approach takes advantage of the shell's tendency to split thestdin
into arguments automatically, removing the need forawk
orcut
.
– Caleb Xu
Apr 11 '14 at 1:38
3
@CalebXu Not stdin,set
sets the shell arguments.
– Guido
Nov 14 '14 at 14:54
8
word1=$(IFS=" " ; set -- $string ; echo $1)
Set IFS to correctly recognize the space between the words. Wrap in parentheses to avoid clobbering the original content of $1.
– Steve Pitchers
May 15 '15 at 10:27
This is broken as it's subject to pathname expansion. Try it withstring="*"
. Surprise.
– gniourf_gniourf
Mar 14 at 17:55
add a comment |
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.
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.
edited Mar 14 '10 at 0:06
answered Mar 13 '10 at 23:59
ghostdog74
215k39210296
215k39210296
5
Can you explain briefly how this works?
– Matt Montag
Mar 2 '14 at 2:37
6
+1 for using only shell built-ins andstdin
. @Matt M.--
meansstdin
, so$string
is being passed in asstdin
.stdin
is whitespace-separated into arguments$1
,$2
,$3
, etc. - just like when a Bash program evaluates arguments (e.g. check$1
,$2
, etc.), this approach takes advantage of the shell's tendency to split thestdin
into arguments automatically, removing the need forawk
orcut
.
– Caleb Xu
Apr 11 '14 at 1:38
3
@CalebXu Not stdin,set
sets the shell arguments.
– Guido
Nov 14 '14 at 14:54
8
word1=$(IFS=" " ; set -- $string ; echo $1)
Set IFS to correctly recognize the space between the words. Wrap in parentheses to avoid clobbering the original content of $1.
– Steve Pitchers
May 15 '15 at 10:27
This is broken as it's subject to pathname expansion. Try it withstring="*"
. Surprise.
– gniourf_gniourf
Mar 14 at 17:55
add a comment |
5
Can you explain briefly how this works?
– Matt Montag
Mar 2 '14 at 2:37
6
+1 for using only shell built-ins andstdin
. @Matt M.--
meansstdin
, so$string
is being passed in asstdin
.stdin
is whitespace-separated into arguments$1
,$2
,$3
, etc. - just like when a Bash program evaluates arguments (e.g. check$1
,$2
, etc.), this approach takes advantage of the shell's tendency to split thestdin
into arguments automatically, removing the need forawk
orcut
.
– Caleb Xu
Apr 11 '14 at 1:38
3
@CalebXu Not stdin,set
sets the shell arguments.
– Guido
Nov 14 '14 at 14:54
8
word1=$(IFS=" " ; set -- $string ; echo $1)
Set IFS to correctly recognize the space between the words. Wrap in parentheses to avoid clobbering the original content of $1.
– Steve Pitchers
May 15 '15 at 10:27
This is broken as it's subject to pathname expansion. Try it withstring="*"
. Surprise.
– gniourf_gniourf
Mar 14 at 17:55
5
5
Can you explain briefly how this works?
– Matt Montag
Mar 2 '14 at 2:37
Can you explain briefly how this works?
– Matt Montag
Mar 2 '14 at 2:37
6
6
+1 for using only shell built-ins and
stdin
. @Matt M. --
means stdin
, so $string
is being passed in as stdin
. stdin
is whitespace-separated into arguments $1
, $2
, $3
, etc. - just like when a Bash program evaluates arguments (e.g. check $1
, $2
, etc.), this approach takes advantage of the shell's tendency to split the stdin
into arguments automatically, removing the need for awk
or cut
.– Caleb Xu
Apr 11 '14 at 1:38
+1 for using only shell built-ins and
stdin
. @Matt M. --
means stdin
, so $string
is being passed in as stdin
. stdin
is whitespace-separated into arguments $1
, $2
, $3
, etc. - just like when a Bash program evaluates arguments (e.g. check $1
, $2
, etc.), this approach takes advantage of the shell's tendency to split the stdin
into arguments automatically, removing the need for awk
or cut
.– Caleb Xu
Apr 11 '14 at 1:38
3
3
@CalebXu Not stdin,
set
sets the shell arguments.– Guido
Nov 14 '14 at 14:54
@CalebXu Not stdin,
set
sets the shell arguments.– Guido
Nov 14 '14 at 14:54
8
8
word1=$(IFS=" " ; set -- $string ; echo $1)
Set IFS to correctly recognize the space between the words. Wrap in parentheses to avoid clobbering the original content of $1.– Steve Pitchers
May 15 '15 at 10:27
word1=$(IFS=" " ; set -- $string ; echo $1)
Set IFS to correctly recognize the space between the words. Wrap in parentheses to avoid clobbering the original content of $1.– Steve Pitchers
May 15 '15 at 10:27
This is broken as it's subject to pathname expansion. Try it with
string="*"
. Surprise.– gniourf_gniourf
Mar 14 at 17:55
This is broken as it's subject to pathname expansion. Try it with
string="*"
. Surprise.– gniourf_gniourf
Mar 14 at 17:55
add a comment |
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
echo " word1 word2 " | { read -a array ; echo ${array[0]} ; }
– Boontawee Home
Feb 21 '16 at 16:44
This is broken as it's subject to pathname expansion. Try it withstring="*"
. Surprise.
– gniourf_gniourf
Mar 14 at 17:56
Use thewhile
syntax to retrieve every first word at each line. Otherwise, use Boontawee Home approach. Also, please note thatecho "${array[0]}"
has been quoted to prevent expansion as noticed by gniourf-gniourf.
– Isaías
Apr 9 at 23:28
If you try to access an index of array which is greater than the number of words, then you won't get an error. You will just get an empty line
– Dhumil Agarwal
May 22 at 6:40
add a comment |
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
echo " word1 word2 " | { read -a array ; echo ${array[0]} ; }
– Boontawee Home
Feb 21 '16 at 16:44
This is broken as it's subject to pathname expansion. Try it withstring="*"
. Surprise.
– gniourf_gniourf
Mar 14 at 17:56
Use thewhile
syntax to retrieve every first word at each line. Otherwise, use Boontawee Home approach. Also, please note thatecho "${array[0]}"
has been quoted to prevent expansion as noticed by gniourf-gniourf.
– Isaías
Apr 9 at 23:28
If you try to access an index of array which is greater than the number of words, then you won't get an error. You will just get an empty line
– Dhumil Agarwal
May 22 at 6:40
add a comment |
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
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
edited Apr 9 at 23:18
answered May 3 '15 at 10:20
Isaías
36035
36035
echo " word1 word2 " | { read -a array ; echo ${array[0]} ; }
– Boontawee Home
Feb 21 '16 at 16:44
This is broken as it's subject to pathname expansion. Try it withstring="*"
. Surprise.
– gniourf_gniourf
Mar 14 at 17:56
Use thewhile
syntax to retrieve every first word at each line. Otherwise, use Boontawee Home approach. Also, please note thatecho "${array[0]}"
has been quoted to prevent expansion as noticed by gniourf-gniourf.
– Isaías
Apr 9 at 23:28
If you try to access an index of array which is greater than the number of words, then you won't get an error. You will just get an empty line
– Dhumil Agarwal
May 22 at 6:40
add a comment |
echo " word1 word2 " | { read -a array ; echo ${array[0]} ; }
– Boontawee Home
Feb 21 '16 at 16:44
This is broken as it's subject to pathname expansion. Try it withstring="*"
. Surprise.
– gniourf_gniourf
Mar 14 at 17:56
Use thewhile
syntax to retrieve every first word at each line. Otherwise, use Boontawee Home approach. Also, please note thatecho "${array[0]}"
has been quoted to prevent expansion as noticed by gniourf-gniourf.
– Isaías
Apr 9 at 23:28
If you try to access an index of array which is greater than the number of words, then you won't get an error. You will just get an empty line
– Dhumil Agarwal
May 22 at 6:40
echo " word1 word2 " | { read -a array ; echo ${array[0]} ; }
– Boontawee Home
Feb 21 '16 at 16:44
echo " word1 word2 " | { read -a array ; echo ${array[0]} ; }
– Boontawee Home
Feb 21 '16 at 16:44
This is broken as it's subject to pathname expansion. Try it with
string="*"
. Surprise.– gniourf_gniourf
Mar 14 at 17:56
This is broken as it's subject to pathname expansion. Try it with
string="*"
. Surprise.– gniourf_gniourf
Mar 14 at 17:56
Use the
while
syntax to retrieve every first word at each line. Otherwise, use Boontawee Home approach. Also, please note that echo "${array[0]}"
has been quoted to prevent expansion as noticed by gniourf-gniourf.– Isaías
Apr 9 at 23:28
Use the
while
syntax to retrieve every first word at each line. Otherwise, use Boontawee Home approach. Also, please note that echo "${array[0]}"
has been quoted to prevent expansion as noticed by gniourf-gniourf.– Isaías
Apr 9 at 23:28
If you try to access an index of array which is greater than the number of words, then you won't get an error. You will just get an empty line
– Dhumil Agarwal
May 22 at 6:40
If you try to access an index of array which is greater than the number of words, then you won't get an error. You will just get an empty line
– Dhumil Agarwal
May 22 at 6:40
add a comment |
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.
2
echo " word1 word2 " | { read first _ ; echo $first ; }
– Boontawee Home
Feb 21 '16 at 16:46
Leaving the variables$1, $2, …
intact is an extremely useful feature for script writing!
– Serge Stroobandt
Oct 21 '16 at 22:59
add a comment |
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.
2
echo " word1 word2 " | { read first _ ; echo $first ; }
– Boontawee Home
Feb 21 '16 at 16:46
Leaving the variables$1, $2, …
intact is an extremely useful feature for script writing!
– Serge Stroobandt
Oct 21 '16 at 22:59
add a comment |
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.
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.
answered May 20 '14 at 2:33
John Marter
49154
49154
2
echo " word1 word2 " | { read first _ ; echo $first ; }
– Boontawee Home
Feb 21 '16 at 16:46
Leaving the variables$1, $2, …
intact is an extremely useful feature for script writing!
– Serge Stroobandt
Oct 21 '16 at 22:59
add a comment |
2
echo " word1 word2 " | { read first _ ; echo $first ; }
– Boontawee Home
Feb 21 '16 at 16:46
Leaving the variables$1, $2, …
intact is an extremely useful feature for script writing!
– Serge Stroobandt
Oct 21 '16 at 22:59
2
2
echo " word1 word2 " | { read first _ ; echo $first ; }
– Boontawee Home
Feb 21 '16 at 16:46
echo " word1 word2 " | { read first _ ; echo $first ; }
– Boontawee Home
Feb 21 '16 at 16:46
Leaving the variables
$1, $2, …
intact is an extremely useful feature for script writing!– Serge Stroobandt
Oct 21 '16 at 22:59
Leaving the variables
$1, $2, …
intact is an extremely useful feature for script writing!– Serge Stroobandt
Oct 21 '16 at 22:59
add a comment |
You could try awk
echo "word1 word2" | awk '{ print $1 }'
With awk it is really easy to pick any word you like ($1, $2, ...)
add a comment |
You could try awk
echo "word1 word2" | awk '{ print $1 }'
With awk it is really easy to pick any word you like ($1, $2, ...)
add a comment |
You could try awk
echo "word1 word2" | awk '{ print $1 }'
With awk it is really easy to pick any word you like ($1, $2, ...)
You could try awk
echo "word1 word2" | awk '{ print $1 }'
With awk it is really easy to pick any word you like ($1, $2, ...)
edited Mar 13 '10 at 23:29
answered Mar 13 '10 at 23:21
mfloryan
6,81242441
6,81242441
add a comment |
add a comment |
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
add a comment |
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
add a comment |
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
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
edited Nov 13 '14 at 15:11
answered Nov 13 '14 at 14:00
dsl101
610613
610613
add a comment |
add a comment |
echo "word1 word2" | cut -f 1 -d " "
cut cuts the 1st field (-f 1) from a list of fields delimited by the string " " (-d " ")
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
Mar 14 '10 at 0:03
yep, the awk solution is the better one.
– lajuette
Mar 10 '14 at 9:29
add a comment |
echo "word1 word2" | cut -f 1 -d " "
cut cuts the 1st field (-f 1) from a list of fields delimited by the string " " (-d " ")
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
Mar 14 '10 at 0:03
yep, the awk solution is the better one.
– lajuette
Mar 10 '14 at 9:29
add a comment |
echo "word1 word2" | cut -f 1 -d " "
cut cuts the 1st field (-f 1) from a list of fields delimited by the string " " (-d " ")
echo "word1 word2" | cut -f 1 -d " "
cut cuts the 1st field (-f 1) from a list of fields delimited by the string " " (-d " ")
answered Mar 13 '10 at 23:11
lajuette
7471416
7471416
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
Mar 14 '10 at 0:03
yep, the awk solution is the better one.
– lajuette
Mar 10 '14 at 9:29
add a comment |
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
Mar 14 '10 at 0:03
yep, the awk solution is the better one.
– lajuette
Mar 10 '14 at 9:29
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
Mar 14 '10 at 0:03
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
Mar 14 '10 at 0:03
yep, the awk solution is the better one.
– lajuette
Mar 10 '14 at 9:29
yep, the awk solution is the better one.
– lajuette
Mar 10 '14 at 9:29
add a comment |
Using shell paramter 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
Explanation
The %%
signifies deleting the longest match of *
(a space followed by whatever number of any other characters), starting from the right-hand side of the variable string
.
add a comment |
Using shell paramter 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
Explanation
The %%
signifies deleting the longest match of *
(a space followed by whatever number of any other characters), starting from the right-hand side of the variable string
.
add a comment |
Using shell paramter 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
Explanation
The %%
signifies deleting the longest match of *
(a space followed by whatever number of any other characters), starting from the right-hand side of the variable string
.
Using shell paramter 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
Explanation
The %%
signifies deleting the longest match of *
(a space followed by whatever number of any other characters), starting from the right-hand side of the variable string
.
edited Nov 22 at 17:35
answered Dec 10 '16 at 18:41
Serge Stroobandt
10.4k64858
10.4k64858
add a comment |
add a comment |
read
is your friend:
If string is in a variable:
string="word1 word2"
read -r first _ <<< "$string"
printf '%sn' "$first"
If you're working in a pipe: first case: you only want the first word of the first line:
printf '%sn' "word1 word2" "line2" | { read -r first _; printf '%sn' "$first"; }
second case: you want the first word of each line:
printf '%sn' "word1 word2" "worda wordb" | while read -r first _; do printf '%sn' "$first"; done
These work if there are leading spaces:
printf '%sn' " word1 word2" | { read -r first _; printf '%sn' "$first"; }
add a comment |
read
is your friend:
If string is in a variable:
string="word1 word2"
read -r first _ <<< "$string"
printf '%sn' "$first"
If you're working in a pipe: first case: you only want the first word of the first line:
printf '%sn' "word1 word2" "line2" | { read -r first _; printf '%sn' "$first"; }
second case: you want the first word of each line:
printf '%sn' "word1 word2" "worda wordb" | while read -r first _; do printf '%sn' "$first"; done
These work if there are leading spaces:
printf '%sn' " word1 word2" | { read -r first _; printf '%sn' "$first"; }
add a comment |
read
is your friend:
If string is in a variable:
string="word1 word2"
read -r first _ <<< "$string"
printf '%sn' "$first"
If you're working in a pipe: first case: you only want the first word of the first line:
printf '%sn' "word1 word2" "line2" | { read -r first _; printf '%sn' "$first"; }
second case: you want the first word of each line:
printf '%sn' "word1 word2" "worda wordb" | while read -r first _; do printf '%sn' "$first"; done
These work if there are leading spaces:
printf '%sn' " word1 word2" | { read -r first _; printf '%sn' "$first"; }
read
is your friend:
If string is in a variable:
string="word1 word2"
read -r first _ <<< "$string"
printf '%sn' "$first"
If you're working in a pipe: first case: you only want the first word of the first line:
printf '%sn' "word1 word2" "line2" | { read -r first _; printf '%sn' "$first"; }
second case: you want the first word of each line:
printf '%sn' "word1 word2" "worda wordb" | while read -r first _; do printf '%sn' "$first"; done
These work if there are leading spaces:
printf '%sn' " word1 word2" | { read -r first _; printf '%sn' "$first"; }
answered Nov 13 '14 at 15:20
gniourf_gniourf
29.4k56483
29.4k56483
add a comment |
add a comment |
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. Did each measurement five times (the results were all for 100 loops, best of 3), and averaged the results:
method time
--------------------------------
1. awk 9.2ms
2. set 11.6ms (1.26 * "1")
3. read -a 11.7ms (1.27 * "1")
4. read 13.6ms (1.48 * "1")
Nice job, voters 👏 The votes (as of this writing) match the solutions' speed!
Weird that you could measure 3 in dash, since dash doesn't support arrays (read -a
is invalid in dash).
– gniourf_gniourf
Mar 14 at 17:58
Yeah that is weird. I ruled that one out, did the speed tests, then thought "why'd I leave that one out" and added it in. Removing it now, and I may rerun things later to make sure I didn't have some mistake
– henry
Mar 14 at 19:31
add a comment |
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. Did each measurement five times (the results were all for 100 loops, best of 3), and averaged the results:
method time
--------------------------------
1. awk 9.2ms
2. set 11.6ms (1.26 * "1")
3. read -a 11.7ms (1.27 * "1")
4. read 13.6ms (1.48 * "1")
Nice job, voters 👏 The votes (as of this writing) match the solutions' speed!
Weird that you could measure 3 in dash, since dash doesn't support arrays (read -a
is invalid in dash).
– gniourf_gniourf
Mar 14 at 17:58
Yeah that is weird. I ruled that one out, did the speed tests, then thought "why'd I leave that one out" and added it in. Removing it now, and I may rerun things later to make sure I didn't have some mistake
– henry
Mar 14 at 19:31
add a comment |
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. Did each measurement five times (the results were all for 100 loops, best of 3), and averaged the results:
method time
--------------------------------
1. awk 9.2ms
2. set 11.6ms (1.26 * "1")
3. read -a 11.7ms (1.27 * "1")
4. read 13.6ms (1.48 * "1")
Nice job, voters 👏 The votes (as of this writing) match the solutions' speed!
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. Did each measurement five times (the results were all for 100 loops, best of 3), and averaged the results:
method time
--------------------------------
1. awk 9.2ms
2. set 11.6ms (1.26 * "1")
3. read -a 11.7ms (1.27 * "1")
4. read 13.6ms (1.48 * "1")
Nice job, voters 👏 The votes (as of this writing) match the solutions' speed!
edited Mar 14 at 19:33
answered Mar 14 at 17:49
henry
2,56411430
2,56411430
Weird that you could measure 3 in dash, since dash doesn't support arrays (read -a
is invalid in dash).
– gniourf_gniourf
Mar 14 at 17:58
Yeah that is weird. I ruled that one out, did the speed tests, then thought "why'd I leave that one out" and added it in. Removing it now, and I may rerun things later to make sure I didn't have some mistake
– henry
Mar 14 at 19:31
add a comment |
Weird that you could measure 3 in dash, since dash doesn't support arrays (read -a
is invalid in dash).
– gniourf_gniourf
Mar 14 at 17:58
Yeah that is weird. I ruled that one out, did the speed tests, then thought "why'd I leave that one out" and added it in. Removing it now, and I may rerun things later to make sure I didn't have some mistake
– henry
Mar 14 at 19:31
Weird that you could measure 3 in dash, since dash doesn't support arrays (
read -a
is invalid in dash).– gniourf_gniourf
Mar 14 at 17:58
Weird that you could measure 3 in dash, since dash doesn't support arrays (
read -a
is invalid in dash).– gniourf_gniourf
Mar 14 at 17:58
Yeah that is weird. I ruled that one out, did the speed tests, then thought "why'd I leave that one out" and added it in. Removing it now, and I may rerun things later to make sure I didn't have some mistake
– henry
Mar 14 at 19:31
Yeah that is weird. I ruled that one out, did the speed tests, then thought "why'd I leave that one out" and added it in. Removing it now, and I may rerun things later to make sure I didn't have some mistake
– henry
Mar 14 at 19:31
add a comment |
As perl incorporates awk's functionality this can be solved with perl too:
echo " word1 word2" | perl -lane 'print $F[0]'
add a comment |
As perl incorporates awk's functionality this can be solved with perl too:
echo " word1 word2" | perl -lane 'print $F[0]'
add a comment |
As perl incorporates awk's functionality this can be solved with perl too:
echo " word1 word2" | perl -lane 'print $F[0]'
As perl incorporates awk's functionality this can be solved with perl too:
echo " word1 word2" | perl -lane 'print $F[0]'
answered Jan 26 '17 at 8:15
tssch
544618
544618
add a comment |
add a comment |
I was working with a 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.
add a comment |
I was working with a 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.
add a comment |
I was working with a 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.
I was working with a 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.
answered Jan 5 at 10:49
Johan Bjäreholt
3071217
3071217
add a comment |
add a comment |
Thanks for contributing an answer to Stack Overflow!
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Some of your past answers have not been well-received, and you're in danger of being blocked from answering.
Please pay close attention to the following guidance:
- Please be sure to answer the question. Provide details and share your research!
But avoid …
- Asking for help, clarification, or responding to other answers.
- Making statements based on opinion; back them up with references or personal experience.
To learn more, see our tips on writing great answers.
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f2440414%2fhow-to-retrieve-the-first-word-of-the-output-of-a-command-in-bash%23new-answer', 'question_page');
}
);
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown
Required, but never shown