Extract file name from path in awk program

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












19














I have an awk script and I have passed a CSV file to it.



awk -f script.awk /home/abc/imp/asgd.csv


What am I doing is to get FILENAME within script.awk. FILENAME gives me the whole path. As I am in awk I cannot use basename FILENAME.



print FILENAME;
/home/abc/imp/asgd.csv


I have tried with this within script.awk



echo $FILENAME | awk -F"/" 'print $NF'


but I cannot execute this within script.awk. How can I get asgd.csv within an awk program?










share|improve this question




























    19














    I have an awk script and I have passed a CSV file to it.



    awk -f script.awk /home/abc/imp/asgd.csv


    What am I doing is to get FILENAME within script.awk. FILENAME gives me the whole path. As I am in awk I cannot use basename FILENAME.



    print FILENAME;
    /home/abc/imp/asgd.csv


    I have tried with this within script.awk



    echo $FILENAME | awk -F"/" 'print $NF'


    but I cannot execute this within script.awk. How can I get asgd.csv within an awk program?










    share|improve this question


























      19












      19








      19


      3





      I have an awk script and I have passed a CSV file to it.



      awk -f script.awk /home/abc/imp/asgd.csv


      What am I doing is to get FILENAME within script.awk. FILENAME gives me the whole path. As I am in awk I cannot use basename FILENAME.



      print FILENAME;
      /home/abc/imp/asgd.csv


      I have tried with this within script.awk



      echo $FILENAME | awk -F"/" 'print $NF'


      but I cannot execute this within script.awk. How can I get asgd.csv within an awk program?










      share|improve this question















      I have an awk script and I have passed a CSV file to it.



      awk -f script.awk /home/abc/imp/asgd.csv


      What am I doing is to get FILENAME within script.awk. FILENAME gives me the whole path. As I am in awk I cannot use basename FILENAME.



      print FILENAME;
      /home/abc/imp/asgd.csv


      I have tried with this within script.awk



      echo $FILENAME | awk -F"/" 'print $NF'


      but I cannot execute this within script.awk. How can I get asgd.csv within an awk program?







      awk filenames






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Jun 3 '14 at 22:42









      Gilles

      529k12810601586




      529k12810601586










      asked Jun 3 '14 at 7:58









      Aashu

      3383523




      3383523




















          5 Answers
          5






          active

          oldest

          votes


















          25














          Several options:



          awk '
          function basename(file)
          sub(".*/", "", file)
          return file

          print FILENAME, basename(FILENAME)' /path/to/file


          Or:



          awk '
          function basename(file, a, n)
          n = split(file, a, "/")
          return a[n]

          print FILENAME, basename(FILENAME)' /path/to/file


          Note that those implementations of basename should work for the common cases, but not in corner cases like basename /path/to/x/// where they return the empty string instead of x or / where they return the empty string instead of /, though for regular files, that should not happen.



          The first one will not work properly if the file paths (up to the last /) contain sequences of bytes that don't form valid characters in the current locale (typically this kind of thing happens in UTF-8 locales with filenames encoded in some 8 bit single byte character set). You can work around that by fixing the locale to C where every sequence of byte form valid characters.






          share|improve this answer


















          • 3




            If you need code that will work easily within an existing awk script without introducing a function, you should use: n = split(FILENAME, a, "/"); basename=a[n];. Don't use sub as that will actually change the FILENAME variable (which is a non-issue with the function since awk uses call by value).
            – shiri
            Jan 7 '18 at 9:28



















          8














          Try this awk one-liner,



          $ awk 'END var=FILENAME; split (var,a,///); print a[5]' /home/abc/imp/asgd.csv
          asgd.csv





          share|improve this answer
















          • 2




            or awk 'END var=FILENAME; n=split (var,a,///); print a[n]' /home/abc/imp/asgd.csv
            – Avinash Raj
            Jun 3 '14 at 8:39


















          0














          the best way to export it from input CSV or directly from input file path you can reverse it , then get 1 column and then again reverse it.



          function getFileFromPath() rev 
          done



          or simply



          echo $FileNamePath| rev | awk -v FS='/' 'print $1' | rev 





          share|improve this answer




























            0














            Use Awk's Split Function



            One way to do this is to use the split function. For example:



            awk 'idx = split(FILENAME, parts, "/"); print parts[idx]; nextfile' /path/to/file


            This even works on multiple files. For example:




            $ awk 'idx = split(FILENAME, parts, "/"); print parts[idx]; nextfile' 
            /etc/passwd /etc/group
            passwd
            group






            share|improve this answer




























              0














              On the systems where basename command is available, one could use awk's system() function or expression | getline var structure to call external basename command. This can help accounting for corner cases mentioned in Stephane's answer.



              $ awk 'cmd=sprintf("basename %s",FILENAME);cmd ' /etc///passwd
              /etc///passwd passwd





              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%2f134212%2fextract-file-name-from-path-in-awk-program%23new-answer', 'question_page');

                );

                Post as a guest















                Required, but never shown

























                5 Answers
                5






                active

                oldest

                votes








                5 Answers
                5






                active

                oldest

                votes









                active

                oldest

                votes






                active

                oldest

                votes









                25














                Several options:



                awk '
                function basename(file)
                sub(".*/", "", file)
                return file

                print FILENAME, basename(FILENAME)' /path/to/file


                Or:



                awk '
                function basename(file, a, n)
                n = split(file, a, "/")
                return a[n]

                print FILENAME, basename(FILENAME)' /path/to/file


                Note that those implementations of basename should work for the common cases, but not in corner cases like basename /path/to/x/// where they return the empty string instead of x or / where they return the empty string instead of /, though for regular files, that should not happen.



                The first one will not work properly if the file paths (up to the last /) contain sequences of bytes that don't form valid characters in the current locale (typically this kind of thing happens in UTF-8 locales with filenames encoded in some 8 bit single byte character set). You can work around that by fixing the locale to C where every sequence of byte form valid characters.






                share|improve this answer


















                • 3




                  If you need code that will work easily within an existing awk script without introducing a function, you should use: n = split(FILENAME, a, "/"); basename=a[n];. Don't use sub as that will actually change the FILENAME variable (which is a non-issue with the function since awk uses call by value).
                  – shiri
                  Jan 7 '18 at 9:28
















                25














                Several options:



                awk '
                function basename(file)
                sub(".*/", "", file)
                return file

                print FILENAME, basename(FILENAME)' /path/to/file


                Or:



                awk '
                function basename(file, a, n)
                n = split(file, a, "/")
                return a[n]

                print FILENAME, basename(FILENAME)' /path/to/file


                Note that those implementations of basename should work for the common cases, but not in corner cases like basename /path/to/x/// where they return the empty string instead of x or / where they return the empty string instead of /, though for regular files, that should not happen.



                The first one will not work properly if the file paths (up to the last /) contain sequences of bytes that don't form valid characters in the current locale (typically this kind of thing happens in UTF-8 locales with filenames encoded in some 8 bit single byte character set). You can work around that by fixing the locale to C where every sequence of byte form valid characters.






                share|improve this answer


















                • 3




                  If you need code that will work easily within an existing awk script without introducing a function, you should use: n = split(FILENAME, a, "/"); basename=a[n];. Don't use sub as that will actually change the FILENAME variable (which is a non-issue with the function since awk uses call by value).
                  – shiri
                  Jan 7 '18 at 9:28














                25












                25








                25






                Several options:



                awk '
                function basename(file)
                sub(".*/", "", file)
                return file

                print FILENAME, basename(FILENAME)' /path/to/file


                Or:



                awk '
                function basename(file, a, n)
                n = split(file, a, "/")
                return a[n]

                print FILENAME, basename(FILENAME)' /path/to/file


                Note that those implementations of basename should work for the common cases, but not in corner cases like basename /path/to/x/// where they return the empty string instead of x or / where they return the empty string instead of /, though for regular files, that should not happen.



                The first one will not work properly if the file paths (up to the last /) contain sequences of bytes that don't form valid characters in the current locale (typically this kind of thing happens in UTF-8 locales with filenames encoded in some 8 bit single byte character set). You can work around that by fixing the locale to C where every sequence of byte form valid characters.






                share|improve this answer














                Several options:



                awk '
                function basename(file)
                sub(".*/", "", file)
                return file

                print FILENAME, basename(FILENAME)' /path/to/file


                Or:



                awk '
                function basename(file, a, n)
                n = split(file, a, "/")
                return a[n]

                print FILENAME, basename(FILENAME)' /path/to/file


                Note that those implementations of basename should work for the common cases, but not in corner cases like basename /path/to/x/// where they return the empty string instead of x or / where they return the empty string instead of /, though for regular files, that should not happen.



                The first one will not work properly if the file paths (up to the last /) contain sequences of bytes that don't form valid characters in the current locale (typically this kind of thing happens in UTF-8 locales with filenames encoded in some 8 bit single byte character set). You can work around that by fixing the locale to C where every sequence of byte form valid characters.







                share|improve this answer














                share|improve this answer



                share|improve this answer








                edited Jun 14 '16 at 15:43

























                answered Jun 3 '14 at 8:35









                Stéphane Chazelas

                300k54564913




                300k54564913







                • 3




                  If you need code that will work easily within an existing awk script without introducing a function, you should use: n = split(FILENAME, a, "/"); basename=a[n];. Don't use sub as that will actually change the FILENAME variable (which is a non-issue with the function since awk uses call by value).
                  – shiri
                  Jan 7 '18 at 9:28













                • 3




                  If you need code that will work easily within an existing awk script without introducing a function, you should use: n = split(FILENAME, a, "/"); basename=a[n];. Don't use sub as that will actually change the FILENAME variable (which is a non-issue with the function since awk uses call by value).
                  – shiri
                  Jan 7 '18 at 9:28








                3




                3




                If you need code that will work easily within an existing awk script without introducing a function, you should use: n = split(FILENAME, a, "/"); basename=a[n];. Don't use sub as that will actually change the FILENAME variable (which is a non-issue with the function since awk uses call by value).
                – shiri
                Jan 7 '18 at 9:28





                If you need code that will work easily within an existing awk script without introducing a function, you should use: n = split(FILENAME, a, "/"); basename=a[n];. Don't use sub as that will actually change the FILENAME variable (which is a non-issue with the function since awk uses call by value).
                – shiri
                Jan 7 '18 at 9:28














                8














                Try this awk one-liner,



                $ awk 'END var=FILENAME; split (var,a,///); print a[5]' /home/abc/imp/asgd.csv
                asgd.csv





                share|improve this answer
















                • 2




                  or awk 'END var=FILENAME; n=split (var,a,///); print a[n]' /home/abc/imp/asgd.csv
                  – Avinash Raj
                  Jun 3 '14 at 8:39















                8














                Try this awk one-liner,



                $ awk 'END var=FILENAME; split (var,a,///); print a[5]' /home/abc/imp/asgd.csv
                asgd.csv





                share|improve this answer
















                • 2




                  or awk 'END var=FILENAME; n=split (var,a,///); print a[n]' /home/abc/imp/asgd.csv
                  – Avinash Raj
                  Jun 3 '14 at 8:39













                8












                8








                8






                Try this awk one-liner,



                $ awk 'END var=FILENAME; split (var,a,///); print a[5]' /home/abc/imp/asgd.csv
                asgd.csv





                share|improve this answer












                Try this awk one-liner,



                $ awk 'END var=FILENAME; split (var,a,///); print a[5]' /home/abc/imp/asgd.csv
                asgd.csv






                share|improve this answer












                share|improve this answer



                share|improve this answer










                answered Jun 3 '14 at 8:31









                Avinash Raj

                2,60731127




                2,60731127







                • 2




                  or awk 'END var=FILENAME; n=split (var,a,///); print a[n]' /home/abc/imp/asgd.csv
                  – Avinash Raj
                  Jun 3 '14 at 8:39












                • 2




                  or awk 'END var=FILENAME; n=split (var,a,///); print a[n]' /home/abc/imp/asgd.csv
                  – Avinash Raj
                  Jun 3 '14 at 8:39







                2




                2




                or awk 'END var=FILENAME; n=split (var,a,///); print a[n]' /home/abc/imp/asgd.csv
                – Avinash Raj
                Jun 3 '14 at 8:39




                or awk 'END var=FILENAME; n=split (var,a,///); print a[n]' /home/abc/imp/asgd.csv
                – Avinash Raj
                Jun 3 '14 at 8:39











                0














                the best way to export it from input CSV or directly from input file path you can reverse it , then get 1 column and then again reverse it.



                function getFileFromPath() rev 
                done



                or simply



                echo $FileNamePath| rev | awk -v FS='/' 'print $1' | rev 





                share|improve this answer

























                  0














                  the best way to export it from input CSV or directly from input file path you can reverse it , then get 1 column and then again reverse it.



                  function getFileFromPath() rev 
                  done



                  or simply



                  echo $FileNamePath| rev | awk -v FS='/' 'print $1' | rev 





                  share|improve this answer























                    0












                    0








                    0






                    the best way to export it from input CSV or directly from input file path you can reverse it , then get 1 column and then again reverse it.



                    function getFileFromPath() rev 
                    done



                    or simply



                    echo $FileNamePath| rev | awk -v FS='/' 'print $1' | rev 





                    share|improve this answer












                    the best way to export it from input CSV or directly from input file path you can reverse it , then get 1 column and then again reverse it.



                    function getFileFromPath() rev 
                    done



                    or simply



                    echo $FileNamePath| rev | awk -v FS='/' 'print $1' | rev 






                    share|improve this answer












                    share|improve this answer



                    share|improve this answer










                    answered Jan 8 '18 at 6:04









                    FariZ

                    112




                    112





















                        0














                        Use Awk's Split Function



                        One way to do this is to use the split function. For example:



                        awk 'idx = split(FILENAME, parts, "/"); print parts[idx]; nextfile' /path/to/file


                        This even works on multiple files. For example:




                        $ awk 'idx = split(FILENAME, parts, "/"); print parts[idx]; nextfile' 
                        /etc/passwd /etc/group
                        passwd
                        group






                        share|improve this answer

























                          0














                          Use Awk's Split Function



                          One way to do this is to use the split function. For example:



                          awk 'idx = split(FILENAME, parts, "/"); print parts[idx]; nextfile' /path/to/file


                          This even works on multiple files. For example:




                          $ awk 'idx = split(FILENAME, parts, "/"); print parts[idx]; nextfile' 
                          /etc/passwd /etc/group
                          passwd
                          group






                          share|improve this answer























                            0












                            0








                            0






                            Use Awk's Split Function



                            One way to do this is to use the split function. For example:



                            awk 'idx = split(FILENAME, parts, "/"); print parts[idx]; nextfile' /path/to/file


                            This even works on multiple files. For example:




                            $ awk 'idx = split(FILENAME, parts, "/"); print parts[idx]; nextfile' 
                            /etc/passwd /etc/group
                            passwd
                            group






                            share|improve this answer












                            Use Awk's Split Function



                            One way to do this is to use the split function. For example:



                            awk 'idx = split(FILENAME, parts, "/"); print parts[idx]; nextfile' /path/to/file


                            This even works on multiple files. For example:




                            $ awk 'idx = split(FILENAME, parts, "/"); print parts[idx]; nextfile' 
                            /etc/passwd /etc/group
                            passwd
                            group







                            share|improve this answer












                            share|improve this answer



                            share|improve this answer










                            answered Nov 20 '18 at 19:49









                            CodeGnome

                            5,65811023




                            5,65811023





















                                0














                                On the systems where basename command is available, one could use awk's system() function or expression | getline var structure to call external basename command. This can help accounting for corner cases mentioned in Stephane's answer.



                                $ awk 'cmd=sprintf("basename %s",FILENAME);cmd ' /etc///passwd
                                /etc///passwd passwd





                                share|improve this answer

























                                  0














                                  On the systems where basename command is available, one could use awk's system() function or expression | getline var structure to call external basename command. This can help accounting for corner cases mentioned in Stephane's answer.



                                  $ awk 'cmd=sprintf("basename %s",FILENAME);cmd ' /etc///passwd
                                  /etc///passwd passwd





                                  share|improve this answer























                                    0












                                    0








                                    0






                                    On the systems where basename command is available, one could use awk's system() function or expression | getline var structure to call external basename command. This can help accounting for corner cases mentioned in Stephane's answer.



                                    $ awk 'cmd=sprintf("basename %s",FILENAME);cmd ' /etc///passwd
                                    /etc///passwd passwd





                                    share|improve this answer












                                    On the systems where basename command is available, one could use awk's system() function or expression | getline var structure to call external basename command. This can help accounting for corner cases mentioned in Stephane's answer.



                                    $ awk 'cmd=sprintf("basename %s",FILENAME);cmd ' /etc///passwd
                                    /etc///passwd passwd






                                    share|improve this answer












                                    share|improve this answer



                                    share|improve this answer










                                    answered Dec 23 '18 at 9:10









                                    Sergiy Kolodyazhnyy

                                    8,31212152




                                    8,31212152



























                                        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.





                                        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%2funix.stackexchange.com%2fquestions%2f134212%2fextract-file-name-from-path-in-awk-program%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?

                                        Displaying single band from multi-band raster using QGIS

                                        How many registers does an x86_64 CPU actually have?