Print columns in awk by header name

The name of the pictureThe name of the pictureThe name of the pictureClash Royale CLAN TAG#URR8PPP












10















I have a text file like so



foo bar baz
1 a alpha
2 b beta
3 c gamma


I can use awk to print certain columns, like 1 and 3, with print $1, $3, but I want to specify the columns to print by specifying the header of the column instead, something like print $foo, $baz. This is useful so I don't have to open the file and count the columns manually to see which column is which, and I don't have to update the script if the column number or order changes. Can I do this with awk (or another shell tool)?










share|improve this question


























    10















    I have a text file like so



    foo bar baz
    1 a alpha
    2 b beta
    3 c gamma


    I can use awk to print certain columns, like 1 and 3, with print $1, $3, but I want to specify the columns to print by specifying the header of the column instead, something like print $foo, $baz. This is useful so I don't have to open the file and count the columns manually to see which column is which, and I don't have to update the script if the column number or order changes. Can I do this with awk (or another shell tool)?










    share|improve this question
























      10












      10








      10


      3






      I have a text file like so



      foo bar baz
      1 a alpha
      2 b beta
      3 c gamma


      I can use awk to print certain columns, like 1 and 3, with print $1, $3, but I want to specify the columns to print by specifying the header of the column instead, something like print $foo, $baz. This is useful so I don't have to open the file and count the columns manually to see which column is which, and I don't have to update the script if the column number or order changes. Can I do this with awk (or another shell tool)?










      share|improve this question














      I have a text file like so



      foo bar baz
      1 a alpha
      2 b beta
      3 c gamma


      I can use awk to print certain columns, like 1 and 3, with print $1, $3, but I want to specify the columns to print by specifying the header of the column instead, something like print $foo, $baz. This is useful so I don't have to open the file and count the columns manually to see which column is which, and I don't have to update the script if the column number or order changes. Can I do this with awk (or another shell tool)?







      text-processing awk






      share|improve this question













      share|improve this question











      share|improve this question




      share|improve this question










      asked Apr 18 '17 at 14:19









      user1350864user1350864

      21626




      21626




















          3 Answers
          3






          active

          oldest

          votes


















          12














          awk '
          NR==1
          for (i=1; i<=NF; i++)
          f[$i] = i


          print $(f["foo"]), $(f["baz"])
          ' file
          foo baz
          1 alpha
          2 beta
          3 gamma


          That is an immensely useful idiom. I have a lot of data in spreadsheets and different spreadsheets might have a common subset of columns I'm interested in but not necessarily in the same order across all spreadsheets or with the same numbers of other columns before/between them so being able to export them as CSV or similar and then simply run an awk script using the column names instead of column numbers is absolutely invaluable.






          share|improve this answer
































            0














            You ask for awk, but you could also use a more specialized tool for this: csvtool.



            csvtool -t ' ' -u ' ' namedcol foo,baz file


            or



            csvtool -t ' ' -u ' ' col 1,3 file





            share|improve this answer






























              0














              Assuming that the file is a TSV ("tab separated values") file, using csvkit:



              $ csvcut -t -c foo,baz file.tsv
              foo,baz
              1,alpha
              2,beta
              3,gamma


              The output will be properly formatted CSV, but could easily be changed back to TSV:



              $ csvcut -t -c foo,baz file.tsv | csvformat -T
              foo baz
              1 alpha
              2 beta
              3 gamma


              The -c option to csvcut can also take numbers and ranges, and can also be used to rearrange the columns of the input data (a feature I often miss in the standard cut utility).






              share|improve this answer






















                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%2f359697%2fprint-columns-in-awk-by-header-name%23new-answer', 'question_page');

                );

                Post as a guest















                Required, but never shown

























                3 Answers
                3






                active

                oldest

                votes








                3 Answers
                3






                active

                oldest

                votes









                active

                oldest

                votes






                active

                oldest

                votes









                12














                awk '
                NR==1
                for (i=1; i<=NF; i++)
                f[$i] = i


                print $(f["foo"]), $(f["baz"])
                ' file
                foo baz
                1 alpha
                2 beta
                3 gamma


                That is an immensely useful idiom. I have a lot of data in spreadsheets and different spreadsheets might have a common subset of columns I'm interested in but not necessarily in the same order across all spreadsheets or with the same numbers of other columns before/between them so being able to export them as CSV or similar and then simply run an awk script using the column names instead of column numbers is absolutely invaluable.






                share|improve this answer





























                  12














                  awk '
                  NR==1
                  for (i=1; i<=NF; i++)
                  f[$i] = i


                  print $(f["foo"]), $(f["baz"])
                  ' file
                  foo baz
                  1 alpha
                  2 beta
                  3 gamma


                  That is an immensely useful idiom. I have a lot of data in spreadsheets and different spreadsheets might have a common subset of columns I'm interested in but not necessarily in the same order across all spreadsheets or with the same numbers of other columns before/between them so being able to export them as CSV or similar and then simply run an awk script using the column names instead of column numbers is absolutely invaluable.






                  share|improve this answer



























                    12












                    12








                    12







                    awk '
                    NR==1
                    for (i=1; i<=NF; i++)
                    f[$i] = i


                    print $(f["foo"]), $(f["baz"])
                    ' file
                    foo baz
                    1 alpha
                    2 beta
                    3 gamma


                    That is an immensely useful idiom. I have a lot of data in spreadsheets and different spreadsheets might have a common subset of columns I'm interested in but not necessarily in the same order across all spreadsheets or with the same numbers of other columns before/between them so being able to export them as CSV or similar and then simply run an awk script using the column names instead of column numbers is absolutely invaluable.






                    share|improve this answer















                    awk '
                    NR==1
                    for (i=1; i<=NF; i++)
                    f[$i] = i


                    print $(f["foo"]), $(f["baz"])
                    ' file
                    foo baz
                    1 alpha
                    2 beta
                    3 gamma


                    That is an immensely useful idiom. I have a lot of data in spreadsheets and different spreadsheets might have a common subset of columns I'm interested in but not necessarily in the same order across all spreadsheets or with the same numbers of other columns before/between them so being able to export them as CSV or similar and then simply run an awk script using the column names instead of column numbers is absolutely invaluable.







                    share|improve this answer














                    share|improve this answer



                    share|improve this answer








                    edited Apr 18 '17 at 14:33

























                    answered Apr 18 '17 at 14:21









                    Ed MortonEd Morton

                    50028




                    50028























                        0














                        You ask for awk, but you could also use a more specialized tool for this: csvtool.



                        csvtool -t ' ' -u ' ' namedcol foo,baz file


                        or



                        csvtool -t ' ' -u ' ' col 1,3 file





                        share|improve this answer



























                          0














                          You ask for awk, but you could also use a more specialized tool for this: csvtool.



                          csvtool -t ' ' -u ' ' namedcol foo,baz file


                          or



                          csvtool -t ' ' -u ' ' col 1,3 file





                          share|improve this answer

























                            0












                            0








                            0







                            You ask for awk, but you could also use a more specialized tool for this: csvtool.



                            csvtool -t ' ' -u ' ' namedcol foo,baz file


                            or



                            csvtool -t ' ' -u ' ' col 1,3 file





                            share|improve this answer













                            You ask for awk, but you could also use a more specialized tool for this: csvtool.



                            csvtool -t ' ' -u ' ' namedcol foo,baz file


                            or



                            csvtool -t ' ' -u ' ' col 1,3 file






                            share|improve this answer












                            share|improve this answer



                            share|improve this answer










                            answered Feb 19 at 15:01









                            RoVoRoVo

                            3,247216




                            3,247216





















                                0














                                Assuming that the file is a TSV ("tab separated values") file, using csvkit:



                                $ csvcut -t -c foo,baz file.tsv
                                foo,baz
                                1,alpha
                                2,beta
                                3,gamma


                                The output will be properly formatted CSV, but could easily be changed back to TSV:



                                $ csvcut -t -c foo,baz file.tsv | csvformat -T
                                foo baz
                                1 alpha
                                2 beta
                                3 gamma


                                The -c option to csvcut can also take numbers and ranges, and can also be used to rearrange the columns of the input data (a feature I often miss in the standard cut utility).






                                share|improve this answer



























                                  0














                                  Assuming that the file is a TSV ("tab separated values") file, using csvkit:



                                  $ csvcut -t -c foo,baz file.tsv
                                  foo,baz
                                  1,alpha
                                  2,beta
                                  3,gamma


                                  The output will be properly formatted CSV, but could easily be changed back to TSV:



                                  $ csvcut -t -c foo,baz file.tsv | csvformat -T
                                  foo baz
                                  1 alpha
                                  2 beta
                                  3 gamma


                                  The -c option to csvcut can also take numbers and ranges, and can also be used to rearrange the columns of the input data (a feature I often miss in the standard cut utility).






                                  share|improve this answer

























                                    0












                                    0








                                    0







                                    Assuming that the file is a TSV ("tab separated values") file, using csvkit:



                                    $ csvcut -t -c foo,baz file.tsv
                                    foo,baz
                                    1,alpha
                                    2,beta
                                    3,gamma


                                    The output will be properly formatted CSV, but could easily be changed back to TSV:



                                    $ csvcut -t -c foo,baz file.tsv | csvformat -T
                                    foo baz
                                    1 alpha
                                    2 beta
                                    3 gamma


                                    The -c option to csvcut can also take numbers and ranges, and can also be used to rearrange the columns of the input data (a feature I often miss in the standard cut utility).






                                    share|improve this answer













                                    Assuming that the file is a TSV ("tab separated values") file, using csvkit:



                                    $ csvcut -t -c foo,baz file.tsv
                                    foo,baz
                                    1,alpha
                                    2,beta
                                    3,gamma


                                    The output will be properly formatted CSV, but could easily be changed back to TSV:



                                    $ csvcut -t -c foo,baz file.tsv | csvformat -T
                                    foo baz
                                    1 alpha
                                    2 beta
                                    3 gamma


                                    The -c option to csvcut can also take numbers and ranges, and can also be used to rearrange the columns of the input data (a feature I often miss in the standard cut utility).







                                    share|improve this answer












                                    share|improve this answer



                                    share|improve this answer










                                    answered Feb 19 at 16:35









                                    KusalanandaKusalananda

                                    135k17255423




                                    135k17255423



























                                        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%2f359697%2fprint-columns-in-awk-by-header-name%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

                                        How to check contact read email or not when send email to Individual?

                                        Bahrain

                                        Postfix configuration issue with fips on centos 7; mailgun relay