awk assign to multiple variables at once2019 Community Moderator ElectionAWK 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?

What are the advantages of simplicial model categories over non-simplicial ones?

Mimic lecturing on blackboard, facing audience

Quoting Keynes in a lecture

What is Cash Advance APR?

Extract more than nine arguments that occur periodically in a sentence to use in macros in order to typset

The IT department bottlenecks progress. How should I handle this?

Does IPv6 have similar concept of network mask?

Fear of getting stuck on one programming language / technology that is not used in my country

How to fade a semiplane defined by line?

Why did the EU agree to delay the Brexit deadline?

How do apertures which seem too large to physically fit work?

Using substitution ciphers to generate new alphabets in a novel

Does the UK parliament need to pass secondary legislation to accept the Article 50 extension

Can a stoichiometric mixture of oxygen and methane exist as a liquid at standard pressure and some (low) temperature?

How to rewrite equation of hyperbola in standard form

Multiplicative persistence

Hero deduces identity of a killer

Creepy dinosaur pc game identification

How do you make your own symbol when Detexify fails?

15% tax on $7.5k earnings. Is that right?

How can I write humor as character trait?

What exact color does ozone gas have?

What should you do when eye contact makes your subordinate uncomfortable?

How much character growth crosses the line into breaking the character



awk assign to multiple variables at once



2019 Community Moderator ElectionAWK 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?










7















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


























    7















    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
























      7












      7








      7








      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 yesterday









      villapxvillapx

      28029




      28029




















          4 Answers
          4






          active

          oldest

          votes


















          8














          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
            yesterday


















          11














          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
































            4














            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
































              2














              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
                19 hours ago






              • 2





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

                – Stephen Kitt
                17 hours ago










              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









              8














              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
                yesterday















              8














              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
                yesterday













              8












              8








              8







              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 yesterday









              Stéphane ChazelasStéphane Chazelas

              311k57586945




              311k57586945












              • Thanks for the additional explanations on compatibility!

                – villapx
                yesterday

















              • Thanks for the additional explanations on compatibility!

                – villapx
                yesterday
















              Thanks for the additional explanations on compatibility!

              – villapx
              yesterday





              Thanks for the additional explanations on compatibility!

              – villapx
              yesterday













              11














              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





























                11














                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



























                  11












                  11








                  11







                  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 yesterday

























                  answered yesterday









                  glenn jackmanglenn jackman

                  52.6k573114




                  52.6k573114





















                      4














                      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





























                        4














                        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



























                          4












                          4








                          4







                          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 17 hours ago

























                          answered yesterday









                          Stephen KittStephen Kitt

                          177k24402480




                          177k24402480





















                              2














                              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
                                19 hours ago






                              • 2





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

                                – Stephen Kitt
                                17 hours ago















                              2














                              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
                                19 hours ago






                              • 2





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

                                – Stephen Kitt
                                17 hours ago













                              2












                              2








                              2







                              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 yesterday









                              Stéphane Chazelas

                              311k57586945




                              311k57586945










                              answered yesterday









                              villapxvillapx

                              28029




                              28029












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

                                – Cbhihe
                                19 hours ago






                              • 2





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

                                – Stephen Kitt
                                17 hours ago

















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

                                – Cbhihe
                                19 hours ago






                              • 2





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

                                – Stephen Kitt
                                17 hours ago
















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

                              – Cbhihe
                              19 hours ago





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

                              – Cbhihe
                              19 hours ago




                              2




                              2





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

                              – Stephen Kitt
                              17 hours ago





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

                              – Stephen Kitt
                              17 hours ago

















                              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

                              getting Checkpoint VPN SSL Network Extender working in the command lineHow to connect to CheckPoint VPN on Ubuntu 18.04LTS?Will the Linux ( red-hat ) Open VPNC Client connect to checkpoint or nortel VPN gateways?VPN client for linux machine + support checkpoint gatewayVPN SSL Network Extender in FirefoxLinux Checkpoint SNX tool configuration issuesCheck Point - Connect under Linux - snx + OTPSNX VPN Ububuntu 18.XXUsing Checkpoint VPN SSL Network Extender CLI with certificateVPN with network manager (nm-applet) is not workingWill the Linux ( red-hat ) Open VPNC Client connect to checkpoint or nortel VPN gateways?VPN client for linux machine + support checkpoint gatewayImport VPN config files to NetworkManager from command lineTrouble connecting to VPN using network-manager, while command line worksStart a VPN connection with PPTP protocol on command linestarting a docker service daemon breaks the vpn networkCan't connect to vpn with Network-managerVPN SSL Network Extender in FirefoxUsing Checkpoint VPN SSL Network Extender CLI with certificate

                              Cannot Extend partition with GParted The 2019 Stack Overflow Developer Survey Results Are In Announcing the arrival of Valued Associate #679: Cesar Manara Planned maintenance scheduled April 17/18, 2019 at 00:00UTC (8:00pm US/Eastern) 2019 Community Moderator Election ResultsCan't increase partition size with GParted?GParted doesn't recognize the unallocated space after my current partitionWhat is the best way to add unallocated space located before to Ubuntu 12.04 partition with GParted live?I can't figure out how to extend my Arch home partition into free spaceGparted Linux Mint 18.1 issueTrying to extend but swap partition is showing as Unknown in Gparted, shows proper from fdiskRearrange partitions in gparted to extend a partitionUnable to extend partition even though unallocated space is next to it using GPartedAllocate free space to root partitiongparted: how to merge unallocated space with a partition

                              Marilyn Monroe Ny fiainany manokana | Jereo koa | Meny fitetezanafanitarana azy.