awk assign to multiple variables at onceAWK Search massive file and write to variable nameThe ERE regex to split() string between a delimiter and end-of-wordHow to Save variables in a script that can be shared between two runs of awk against the same input file in the script?Using bash variable with escape character in awk to extract lines from fileAdding Contents of multiple files using awkpassing two variable streams as input to awk within a scriptAwk Command - combine two commandssetting more variables insite awk if ? :processing multiple files with awk problemWhy does gawk treat `0123` as a decimal number when coming from the input data?

How to run a prison with the smallest amount of guards?

India just shot down a satellite from the ground. At what altitude range is the resulting debris field?

Term for the "extreme-extension" version of a straw man fallacy?

Is HostGator storing my password in plaintext?

Would this custom Sorcerer variant that can only learn any verbal-component-only spell be unbalanced?

Sort a list by elements of another list

Opposite of a diet

Is this apparent Class Action settlement a spam message?

Is there a problem with hiding "forgot password" until it's needed?

Sequence of Tenses: Translating the subjunctive

Hostile work environment after whistle-blowing on coworker and our boss. What do I do?

Two monoidal structures and copowering

Do the temporary hit points from the Battlerager barbarian's Reckless Abandon stack if I make multiple attacks on my turn?

Class Action - which options I have?

How can I get through very long and very dry, but also very useful technical documents when learning a new tool?

System.debug(JSON.Serialize(o)) Not longer shows full string

Customer Requests (Sometimes) Drive Me Bonkers!

Increase performance creating Mandelbrot set in python

Avoiding estate tax by giving multiple gifts

Why, precisely, is argon used in neutrino experiments?

Would a high gravity rocky planet be guaranteed to have an atmosphere?

How do I rename a Linux host without needing to reboot for the rename to take effect?

How to be diplomatic in refusing to write code that breaches the privacy of our users

Unreliable Magic - Is it worth it?



awk assign to multiple variables at once


AWK Search massive file and write to variable nameThe ERE regex to split() string between a delimiter and end-of-wordHow to Save variables in a script that can be shared between two runs of awk against the same input file in the script?Using bash variable with escape character in awk to extract lines from fileAdding Contents of multiple files using awkpassing two variable streams as input to awk within a scriptAwk Command - combine two commandssetting more variables insite awk if ? :processing multiple files with awk problemWhy does gawk treat `0123` as a decimal number when coming from the input data?













9















I'm trying to pull two numerical values out of a string and assign them to variables using awk (gawk is what I'm using specifically). I want to pull the major and minor version numbers out of a tmux version string into awk variables, e.g.:



  • input: tmux 2.8; maj == 2 and min == 8

  • input: tmux 1.9a; maj == 1 and min == 9

  • input: tmux 2.10; maj == 2 and min == 10

Assuming my input comes from tmux -V on stdin, I currently have the following:



tmux -V | awk '
maj = +gensub(/([0-9]+)..*/, "\1", "g", $2);
min = +gensub(/.*.([0-9]+).*/, "\1", "g", $2);
# ...do something with maj and min...
'


This works, but as many users of tmux know, using if-shell in the .tmux.conf file (where I hope to use this stuff) can easily lead to really long lines in the config file, so I'm wondering if there's a way to combine these two variable assignments into one statement to save space...or any other way to glean these two variables from the input and save space.



I'm thinking of something like:



awk ' maj, min = +gensub(/([0-9]+).([0-9]+).*/, "\1 \2", "g", $2); '


...kind of like in Python, but that particular syntax doesn't exist in awk. Is there anything else that's possible?



Note that readability isn't really a concern, just length.










share|improve this question


























    9















    I'm trying to pull two numerical values out of a string and assign them to variables using awk (gawk is what I'm using specifically). I want to pull the major and minor version numbers out of a tmux version string into awk variables, e.g.:



    • input: tmux 2.8; maj == 2 and min == 8

    • input: tmux 1.9a; maj == 1 and min == 9

    • input: tmux 2.10; maj == 2 and min == 10

    Assuming my input comes from tmux -V on stdin, I currently have the following:



    tmux -V | awk '
    maj = +gensub(/([0-9]+)..*/, "\1", "g", $2);
    min = +gensub(/.*.([0-9]+).*/, "\1", "g", $2);
    # ...do something with maj and min...
    '


    This works, but as many users of tmux know, using if-shell in the .tmux.conf file (where I hope to use this stuff) can easily lead to really long lines in the config file, so I'm wondering if there's a way to combine these two variable assignments into one statement to save space...or any other way to glean these two variables from the input and save space.



    I'm thinking of something like:



    awk ' maj, min = +gensub(/([0-9]+).([0-9]+).*/, "\1 \2", "g", $2); '


    ...kind of like in Python, but that particular syntax doesn't exist in awk. Is there anything else that's possible?



    Note that readability isn't really a concern, just length.










    share|improve this question
























      9












      9








      9








      I'm trying to pull two numerical values out of a string and assign them to variables using awk (gawk is what I'm using specifically). I want to pull the major and minor version numbers out of a tmux version string into awk variables, e.g.:



      • input: tmux 2.8; maj == 2 and min == 8

      • input: tmux 1.9a; maj == 1 and min == 9

      • input: tmux 2.10; maj == 2 and min == 10

      Assuming my input comes from tmux -V on stdin, I currently have the following:



      tmux -V | awk '
      maj = +gensub(/([0-9]+)..*/, "\1", "g", $2);
      min = +gensub(/.*.([0-9]+).*/, "\1", "g", $2);
      # ...do something with maj and min...
      '


      This works, but as many users of tmux know, using if-shell in the .tmux.conf file (where I hope to use this stuff) can easily lead to really long lines in the config file, so I'm wondering if there's a way to combine these two variable assignments into one statement to save space...or any other way to glean these two variables from the input and save space.



      I'm thinking of something like:



      awk ' maj, min = +gensub(/([0-9]+).([0-9]+).*/, "\1 \2", "g", $2); '


      ...kind of like in Python, but that particular syntax doesn't exist in awk. Is there anything else that's possible?



      Note that readability isn't really a concern, just length.










      share|improve this question














      I'm trying to pull two numerical values out of a string and assign them to variables using awk (gawk is what I'm using specifically). I want to pull the major and minor version numbers out of a tmux version string into awk variables, e.g.:



      • input: tmux 2.8; maj == 2 and min == 8

      • input: tmux 1.9a; maj == 1 and min == 9

      • input: tmux 2.10; maj == 2 and min == 10

      Assuming my input comes from tmux -V on stdin, I currently have the following:



      tmux -V | awk '
      maj = +gensub(/([0-9]+)..*/, "\1", "g", $2);
      min = +gensub(/.*.([0-9]+).*/, "\1", "g", $2);
      # ...do something with maj and min...
      '


      This works, but as many users of tmux know, using if-shell in the .tmux.conf file (where I hope to use this stuff) can easily lead to really long lines in the config file, so I'm wondering if there's a way to combine these two variable assignments into one statement to save space...or any other way to glean these two variables from the input and save space.



      I'm thinking of something like:



      awk ' maj, min = +gensub(/([0-9]+).([0-9]+).*/, "\1 \2", "g", $2); '


      ...kind of like in Python, but that particular syntax doesn't exist in awk. Is there anything else that's possible?



      Note that readability isn't really a concern, just length.







      awk gawk






      share|improve this question













      share|improve this question











      share|improve this question




      share|improve this question










      asked Mar 21 at 17:03









      villapxvillapx

      300210




      300210




















          4 Answers
          4






          active

          oldest

          votes


















          9














          Note that gensub is a gawk extension, it won't work with any other awk implementation. Also note that the + unary operator doesn't force numeric conversion in all awk implementations, using + 0 is more portable.



          Here you could do:



          tmux -V | awk -F '[ .]' 'maj = $2+0; min = $3+0; print maj, min'


          If you don't mind using GNU awk extensions, you could also do:



          tmux -V | awk -v FPAT='[0-9]+' 'maj = $1; min = $2; print maj, min'





          share|improve this answer























          • Thanks for the additional explanations on compatibility!

            – villapx
            Mar 21 at 20:45


















          13














          Since you're using GNU awk, you can use the 3-arg form of match() to store multiple capturing groups:



          awk '
          match($0, /([0-9]+).([0-9]+)/, m) maj=m[1]; min=m[2]; print maj, min
          ' <<END
          tmux 2.8
          tmux 1.9a
          tmux 2.10
          END




          2 8
          1 9
          2 10


          https://www.gnu.org/software/gawk/manual/html_node/String-Functions.html






          share|improve this answer
































            5














            You can split the version into an array:



            awk ' split($2, ver, /[.a-z]/) '


            then use ver[1] instead of maj, ver[2] instead of min.



            Adding a-z to the separator removes any lowercase letter from the version number. (The other solutions are better here since they explicitly extract numbers.)






            share|improve this answer
































              3














              Another user posted this answer, and it later was deleted. I thought it was useful:



              Using the split() function, split the version string into an array ver, then access ver[1] and ver[2] rather than maj and min, respectively (or simply store the values in those variables):



              tmux -V | awk ' split($2, ver, /[.a-z]/); print ver[1], ver[2] '


              The plus here is that split() isn't a gawk extension (though its optional fourth argument seps is).






              share|improve this answer

























              • +1 but why use /[.a-z]/ as the third (field separation) argument of the split string function, instead of just "." ?

                – Cbhihe
                Mar 22 at 7:22






              • 2





                @Cbhihe see the explanation on my answer (which I undeleted since villapx thinks it’s useful, thanks villapx!).

                – Stephen Kitt
                Mar 22 at 8:34










              Your Answer








              StackExchange.ready(function()
              var channelOptions =
              tags: "".split(" "),
              id: "106"
              ;
              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: false,
              noModals: true,
              showLowRepImageUploadWarning: true,
              reputationToPostImages: null,
              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%2funix.stackexchange.com%2fquestions%2f507768%2fawk-assign-to-multiple-variables-at-once%23new-answer', 'question_page');

              );

              Post as a guest















              Required, but never shown

























              4 Answers
              4






              active

              oldest

              votes








              4 Answers
              4






              active

              oldest

              votes









              active

              oldest

              votes






              active

              oldest

              votes









              9














              Note that gensub is a gawk extension, it won't work with any other awk implementation. Also note that the + unary operator doesn't force numeric conversion in all awk implementations, using + 0 is more portable.



              Here you could do:



              tmux -V | awk -F '[ .]' 'maj = $2+0; min = $3+0; print maj, min'


              If you don't mind using GNU awk extensions, you could also do:



              tmux -V | awk -v FPAT='[0-9]+' 'maj = $1; min = $2; print maj, min'





              share|improve this answer























              • Thanks for the additional explanations on compatibility!

                – villapx
                Mar 21 at 20:45















              9














              Note that gensub is a gawk extension, it won't work with any other awk implementation. Also note that the + unary operator doesn't force numeric conversion in all awk implementations, using + 0 is more portable.



              Here you could do:



              tmux -V | awk -F '[ .]' 'maj = $2+0; min = $3+0; print maj, min'


              If you don't mind using GNU awk extensions, you could also do:



              tmux -V | awk -v FPAT='[0-9]+' 'maj = $1; min = $2; print maj, min'





              share|improve this answer























              • Thanks for the additional explanations on compatibility!

                – villapx
                Mar 21 at 20:45













              9












              9








              9







              Note that gensub is a gawk extension, it won't work with any other awk implementation. Also note that the + unary operator doesn't force numeric conversion in all awk implementations, using + 0 is more portable.



              Here you could do:



              tmux -V | awk -F '[ .]' 'maj = $2+0; min = $3+0; print maj, min'


              If you don't mind using GNU awk extensions, you could also do:



              tmux -V | awk -v FPAT='[0-9]+' 'maj = $1; min = $2; print maj, min'





              share|improve this answer













              Note that gensub is a gawk extension, it won't work with any other awk implementation. Also note that the + unary operator doesn't force numeric conversion in all awk implementations, using + 0 is more portable.



              Here you could do:



              tmux -V | awk -F '[ .]' 'maj = $2+0; min = $3+0; print maj, min'


              If you don't mind using GNU awk extensions, you could also do:



              tmux -V | awk -v FPAT='[0-9]+' 'maj = $1; min = $2; print maj, min'






              share|improve this answer












              share|improve this answer



              share|improve this answer










              answered Mar 21 at 17:35









              Stéphane ChazelasStéphane Chazelas

              311k57589946




              311k57589946












              • Thanks for the additional explanations on compatibility!

                – villapx
                Mar 21 at 20:45

















              • Thanks for the additional explanations on compatibility!

                – villapx
                Mar 21 at 20:45
















              Thanks for the additional explanations on compatibility!

              – villapx
              Mar 21 at 20:45





              Thanks for the additional explanations on compatibility!

              – villapx
              Mar 21 at 20:45













              13














              Since you're using GNU awk, you can use the 3-arg form of match() to store multiple capturing groups:



              awk '
              match($0, /([0-9]+).([0-9]+)/, m) maj=m[1]; min=m[2]; print maj, min
              ' <<END
              tmux 2.8
              tmux 1.9a
              tmux 2.10
              END




              2 8
              1 9
              2 10


              https://www.gnu.org/software/gawk/manual/html_node/String-Functions.html






              share|improve this answer





























                13














                Since you're using GNU awk, you can use the 3-arg form of match() to store multiple capturing groups:



                awk '
                match($0, /([0-9]+).([0-9]+)/, m) maj=m[1]; min=m[2]; print maj, min
                ' <<END
                tmux 2.8
                tmux 1.9a
                tmux 2.10
                END




                2 8
                1 9
                2 10


                https://www.gnu.org/software/gawk/manual/html_node/String-Functions.html






                share|improve this answer



























                  13












                  13








                  13







                  Since you're using GNU awk, you can use the 3-arg form of match() to store multiple capturing groups:



                  awk '
                  match($0, /([0-9]+).([0-9]+)/, m) maj=m[1]; min=m[2]; print maj, min
                  ' <<END
                  tmux 2.8
                  tmux 1.9a
                  tmux 2.10
                  END




                  2 8
                  1 9
                  2 10


                  https://www.gnu.org/software/gawk/manual/html_node/String-Functions.html






                  share|improve this answer















                  Since you're using GNU awk, you can use the 3-arg form of match() to store multiple capturing groups:



                  awk '
                  match($0, /([0-9]+).([0-9]+)/, m) maj=m[1]; min=m[2]; print maj, min
                  ' <<END
                  tmux 2.8
                  tmux 1.9a
                  tmux 2.10
                  END




                  2 8
                  1 9
                  2 10


                  https://www.gnu.org/software/gawk/manual/html_node/String-Functions.html







                  share|improve this answer














                  share|improve this answer



                  share|improve this answer








                  edited Mar 21 at 17:39

























                  answered Mar 21 at 17:25









                  glenn jackmanglenn jackman

                  52.7k573114




                  52.7k573114





















                      5














                      You can split the version into an array:



                      awk ' split($2, ver, /[.a-z]/) '


                      then use ver[1] instead of maj, ver[2] instead of min.



                      Adding a-z to the separator removes any lowercase letter from the version number. (The other solutions are better here since they explicitly extract numbers.)






                      share|improve this answer





























                        5














                        You can split the version into an array:



                        awk ' split($2, ver, /[.a-z]/) '


                        then use ver[1] instead of maj, ver[2] instead of min.



                        Adding a-z to the separator removes any lowercase letter from the version number. (The other solutions are better here since they explicitly extract numbers.)






                        share|improve this answer



























                          5












                          5








                          5







                          You can split the version into an array:



                          awk ' split($2, ver, /[.a-z]/) '


                          then use ver[1] instead of maj, ver[2] instead of min.



                          Adding a-z to the separator removes any lowercase letter from the version number. (The other solutions are better here since they explicitly extract numbers.)






                          share|improve this answer















                          You can split the version into an array:



                          awk ' split($2, ver, /[.a-z]/) '


                          then use ver[1] instead of maj, ver[2] instead of min.



                          Adding a-z to the separator removes any lowercase letter from the version number. (The other solutions are better here since they explicitly extract numbers.)







                          share|improve this answer














                          share|improve this answer



                          share|improve this answer








                          edited Mar 22 at 8:34

























                          answered Mar 21 at 17:07









                          Stephen KittStephen Kitt

                          178k24405481




                          178k24405481





















                              3














                              Another user posted this answer, and it later was deleted. I thought it was useful:



                              Using the split() function, split the version string into an array ver, then access ver[1] and ver[2] rather than maj and min, respectively (or simply store the values in those variables):



                              tmux -V | awk ' split($2, ver, /[.a-z]/); print ver[1], ver[2] '


                              The plus here is that split() isn't a gawk extension (though its optional fourth argument seps is).






                              share|improve this answer

























                              • +1 but why use /[.a-z]/ as the third (field separation) argument of the split string function, instead of just "." ?

                                – Cbhihe
                                Mar 22 at 7:22






                              • 2





                                @Cbhihe see the explanation on my answer (which I undeleted since villapx thinks it’s useful, thanks villapx!).

                                – Stephen Kitt
                                Mar 22 at 8:34















                              3














                              Another user posted this answer, and it later was deleted. I thought it was useful:



                              Using the split() function, split the version string into an array ver, then access ver[1] and ver[2] rather than maj and min, respectively (or simply store the values in those variables):



                              tmux -V | awk ' split($2, ver, /[.a-z]/); print ver[1], ver[2] '


                              The plus here is that split() isn't a gawk extension (though its optional fourth argument seps is).






                              share|improve this answer

























                              • +1 but why use /[.a-z]/ as the third (field separation) argument of the split string function, instead of just "." ?

                                – Cbhihe
                                Mar 22 at 7:22






                              • 2





                                @Cbhihe see the explanation on my answer (which I undeleted since villapx thinks it’s useful, thanks villapx!).

                                – Stephen Kitt
                                Mar 22 at 8:34













                              3












                              3








                              3







                              Another user posted this answer, and it later was deleted. I thought it was useful:



                              Using the split() function, split the version string into an array ver, then access ver[1] and ver[2] rather than maj and min, respectively (or simply store the values in those variables):



                              tmux -V | awk ' split($2, ver, /[.a-z]/); print ver[1], ver[2] '


                              The plus here is that split() isn't a gawk extension (though its optional fourth argument seps is).






                              share|improve this answer















                              Another user posted this answer, and it later was deleted. I thought it was useful:



                              Using the split() function, split the version string into an array ver, then access ver[1] and ver[2] rather than maj and min, respectively (or simply store the values in those variables):



                              tmux -V | awk ' split($2, ver, /[.a-z]/); print ver[1], ver[2] '


                              The plus here is that split() isn't a gawk extension (though its optional fourth argument seps is).







                              share|improve this answer














                              share|improve this answer



                              share|improve this answer








                              edited Mar 21 at 22:32









                              Stéphane Chazelas

                              311k57589946




                              311k57589946










                              answered Mar 21 at 20:41









                              villapxvillapx

                              300210




                              300210












                              • +1 but why use /[.a-z]/ as the third (field separation) argument of the split string function, instead of just "." ?

                                – Cbhihe
                                Mar 22 at 7:22






                              • 2





                                @Cbhihe see the explanation on my answer (which I undeleted since villapx thinks it’s useful, thanks villapx!).

                                – Stephen Kitt
                                Mar 22 at 8:34

















                              • +1 but why use /[.a-z]/ as the third (field separation) argument of the split string function, instead of just "." ?

                                – Cbhihe
                                Mar 22 at 7:22






                              • 2





                                @Cbhihe see the explanation on my answer (which I undeleted since villapx thinks it’s useful, thanks villapx!).

                                – Stephen Kitt
                                Mar 22 at 8:34
















                              +1 but why use /[.a-z]/ as the third (field separation) argument of the split string function, instead of just "." ?

                              – Cbhihe
                              Mar 22 at 7:22





                              +1 but why use /[.a-z]/ as the third (field separation) argument of the split string function, instead of just "." ?

                              – Cbhihe
                              Mar 22 at 7:22




                              2




                              2





                              @Cbhihe see the explanation on my answer (which I undeleted since villapx thinks it’s useful, thanks villapx!).

                              – Stephen Kitt
                              Mar 22 at 8:34





                              @Cbhihe see the explanation on my answer (which I undeleted since villapx thinks it’s useful, thanks villapx!).

                              – Stephen Kitt
                              Mar 22 at 8:34

















                              draft saved

                              draft discarded
















































                              Thanks for contributing an answer to Unix & Linux Stack Exchange!


                              • 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%2funix.stackexchange.com%2fquestions%2f507768%2fawk-assign-to-multiple-variables-at-once%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

                              Adding axes to figuresAdding axes labels to LaTeX figuresLaTeX equivalent of ConTeXt buffersRotate a node but not its content: the case of the ellipse decorationHow to define the default vertical distance between nodes?TikZ scaling graphic and adjust node position and keep font sizeNumerical conditional within tikz keys?adding axes to shapesAlign axes across subfiguresAdding figures with a certain orderLine up nested tikz enviroments or how to get rid of themAdding axes labels to LaTeX figures

                              Tähtien Talli Jäsenet | Lähteet | NavigointivalikkoSuomen Hippos – Tähtien Talli

                              Do these cracks on my tires look bad? The Next CEO of Stack OverflowDry rot tire should I replace?Having to replace tiresFishtailed so easily? Bad tires? ABS?Filling the tires with something other than air, to avoid puncture hassles?Used Michelin tires safe to install?Do these tyre cracks necessitate replacement?Rumbling noise: tires or mechanicalIs it possible to fix noisy feathered tires?Are bad winter tires still better than summer tires in winter?Torque converter failure - Related to replacing only 2 tires?Why use snow tires on all 4 wheels on 2-wheel-drive cars?