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












84














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.










share|improve this question





























    84














    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.










    share|improve this question



























      84












      84








      84


      14





      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.










      share|improve this question















      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






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Oct 16 '16 at 16:31









      user123456

      197213




      197213










      asked Mar 13 '10 at 23:09









      Neuquino

      4,025134671




      4,025134671
























          12 Answers
          12






          active

          oldest

          votes


















          146














          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.






          share|improve this answer























          • 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



















          59














          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.






          share|improve this answer



















          • 5




            Can you explain briefly how this works?
            – Matt Montag
            Mar 2 '14 at 2:37






          • 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








          • 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 with string="*". Surprise.
            – gniourf_gniourf
            Mar 14 at 17:55



















          26














          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





          share|improve this answer























          • 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










          • 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



















          15














          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.






          share|improve this answer

















          • 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



















          9














          You could try awk



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


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






          share|improve this answer































            9














            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





            share|improve this answer































              4














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


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






              share|improve this answer





















              • 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



















              4














              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.






              share|improve this answer































                3














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





                share|improve this answer





























                  3














                  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!






                  share|improve this answer























                  • 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



















                  0














                  As perl incorporates awk's functionality this can be solved with perl too:



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





                  share|improve this answer





























                    0














                    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.






                    share|improve this answer





















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


                      }
                      });














                      draft saved

                      draft discarded


















                      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









                      146














                      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.






                      share|improve this answer























                      • 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
















                      146














                      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.






                      share|improve this answer























                      • 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














                      146












                      146








                      146






                      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.






                      share|improve this answer














                      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.







                      share|improve this answer














                      share|improve this answer



                      share|improve this answer








                      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


















                      • 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













                      59














                      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.






                      share|improve this answer



















                      • 5




                        Can you explain briefly how this works?
                        – Matt Montag
                        Mar 2 '14 at 2:37






                      • 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








                      • 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 with string="*". Surprise.
                        – gniourf_gniourf
                        Mar 14 at 17:55
















                      59














                      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.






                      share|improve this answer



















                      • 5




                        Can you explain briefly how this works?
                        – Matt Montag
                        Mar 2 '14 at 2:37






                      • 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








                      • 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 with string="*". Surprise.
                        – gniourf_gniourf
                        Mar 14 at 17:55














                      59












                      59








                      59






                      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.






                      share|improve this answer














                      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.







                      share|improve this answer














                      share|improve this answer



                      share|improve this answer








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




                        @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 with string="*". Surprise.
                        – gniourf_gniourf
                        Mar 14 at 17:55














                      • 5




                        Can you explain briefly how this works?
                        – Matt Montag
                        Mar 2 '14 at 2:37






                      • 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








                      • 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 with string="*". 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











                      26














                      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





                      share|improve this answer























                      • 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










                      • 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
















                      26














                      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





                      share|improve this answer























                      • 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










                      • 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














                      26












                      26








                      26






                      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





                      share|improve this answer














                      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






                      share|improve this answer














                      share|improve this answer



                      share|improve this answer








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












                      • 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












                      • 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












                      • 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











                      15














                      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.






                      share|improve this answer

















                      • 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
















                      15














                      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.






                      share|improve this answer

















                      • 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














                      15












                      15








                      15






                      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.






                      share|improve this answer












                      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.







                      share|improve this answer












                      share|improve this answer



                      share|improve this answer










                      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














                      • 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











                      9














                      You could try awk



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


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






                      share|improve this answer




























                        9














                        You could try awk



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


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






                        share|improve this answer


























                          9












                          9








                          9






                          You could try awk



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


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






                          share|improve this answer














                          You could try awk



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


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







                          share|improve this answer














                          share|improve this answer



                          share|improve this answer








                          edited Mar 13 '10 at 23:29

























                          answered Mar 13 '10 at 23:21









                          mfloryan

                          6,81242441




                          6,81242441























                              9














                              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





                              share|improve this answer




























                                9














                                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





                                share|improve this answer


























                                  9












                                  9








                                  9






                                  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





                                  share|improve this answer














                                  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






                                  share|improve this answer














                                  share|improve this answer



                                  share|improve this answer








                                  edited Nov 13 '14 at 15:11

























                                  answered Nov 13 '14 at 14:00









                                  dsl101

                                  610613




                                  610613























                                      4














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


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






                                      share|improve this answer





















                                      • 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
















                                      4














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


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






                                      share|improve this answer





















                                      • 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














                                      4












                                      4








                                      4






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


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






                                      share|improve this answer












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


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







                                      share|improve this answer












                                      share|improve this answer



                                      share|improve this answer










                                      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


















                                      • 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











                                      4














                                      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.






                                      share|improve this answer




























                                        4














                                        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.






                                        share|improve this answer


























                                          4












                                          4








                                          4






                                          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.






                                          share|improve this answer














                                          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.







                                          share|improve this answer














                                          share|improve this answer



                                          share|improve this answer








                                          edited Nov 22 at 17:35

























                                          answered Dec 10 '16 at 18:41









                                          Serge Stroobandt

                                          10.4k64858




                                          10.4k64858























                                              3














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





                                              share|improve this answer


























                                                3














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





                                                share|improve this answer
























                                                  3












                                                  3








                                                  3






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





                                                  share|improve this answer












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






                                                  share|improve this answer












                                                  share|improve this answer



                                                  share|improve this answer










                                                  answered Nov 13 '14 at 15:20









                                                  gniourf_gniourf

                                                  29.4k56483




                                                  29.4k56483























                                                      3














                                                      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!






                                                      share|improve this answer























                                                      • 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
















                                                      3














                                                      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!






                                                      share|improve this answer























                                                      • 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














                                                      3












                                                      3








                                                      3






                                                      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!






                                                      share|improve this answer














                                                      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!







                                                      share|improve this answer














                                                      share|improve this answer



                                                      share|improve this answer








                                                      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


















                                                      • 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











                                                      0














                                                      As perl incorporates awk's functionality this can be solved with perl too:



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





                                                      share|improve this answer


























                                                        0














                                                        As perl incorporates awk's functionality this can be solved with perl too:



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





                                                        share|improve this answer
























                                                          0












                                                          0








                                                          0






                                                          As perl incorporates awk's functionality this can be solved with perl too:



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





                                                          share|improve this answer












                                                          As perl incorporates awk's functionality this can be solved with perl too:



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






                                                          share|improve this answer












                                                          share|improve this answer



                                                          share|improve this answer










                                                          answered Jan 26 '17 at 8:15









                                                          tssch

                                                          544618




                                                          544618























                                                              0














                                                              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.






                                                              share|improve this answer


























                                                                0














                                                                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.






                                                                share|improve this answer
























                                                                  0












                                                                  0








                                                                  0






                                                                  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.






                                                                  share|improve this answer












                                                                  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.







                                                                  share|improve this answer












                                                                  share|improve this answer



                                                                  share|improve this answer










                                                                  answered Jan 5 at 10:49









                                                                  Johan Bjäreholt

                                                                  3071217




                                                                  3071217






























                                                                      draft saved

                                                                      draft discarded




















































                                                                      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.




                                                                      draft saved


                                                                      draft discarded














                                                                      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





















































                                                                      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







                                                                      Popular posts from this blog

                                                                      What visual should I use to simply compare current year value vs last year in Power BI desktop

                                                                      Alexandru Averescu

                                                                      Trompette piccolo