Get last field using awk substr

前端 未结 8 492
天涯浪人
天涯浪人 2020-11-29 02:20

I am trying to use awk to get the name of a file given the absolute path to the file.
For example, when given the input path /home/parent/child/filena

相关标签:
8条回答
  • 2020-11-29 02:31

    If you're open to a Perl solution, here one similar to fedorqui's awk solution:

    perl -F/ -lane 'print $F[-1]' input
    

    -F/ specifies / as the field separator
    $F[-1] is the last element in the @F autosplit array

    0 讨论(0)
  • 2020-11-29 02:37

    It should be a comment to the basename answer but I haven't enough point.

    If you do not use double quotes, basename will not work with path where there is space character:

    $ basename /home/foo/bar foo/bar.png
    bar
    

    ok with quotes " "

    $ basename "/home/foo/bar foo/bar.png"
    bar.png
    

    file example

    $ cat a
    /home/parent/child 1/child 2/child 3/filename1
    /home/parent/child 1/child2/filename2
    /home/parent/child1/filename3
    
    $ while read b ; do basename "$b" ; done < a
    filename1
    filename2
    filename3
    
    0 讨论(0)
  • 2020-11-29 02:41

    In this case it is better to use basename instead of awk:

     $ basename /home/parent/child1/child2/filename
     filename
    
    0 讨论(0)
  • 2020-11-29 02:42

    I know I'm like 3 years late on this but.... you should consider parameter expansion, it's built-in and faster.

    if your input is in a var, let's say, $var1, just do ${var1##*/}. Look below

    $ var1='/home/parent/child1/filename'
    $ echo ${var1##*/}
    filename
    $ var1='/home/parent/child1/child2/filename'
    $ echo ${var1##*/}
    filename
    $ var1='/home/parent/child1/child2/child3/filename'
    $ echo ${var1##*/}
    filename
    
    0 讨论(0)
  • 2020-11-29 02:43

    You can also use:

        sed -n 's/.*\/\([^\/]\{1,\}\)$/\1/p'
    

    or

        sed -n 's/.*\/\([^\/]*\)$/\1/p'
    
    0 讨论(0)
  • 2020-11-29 02:54

    Like 5 years late, I know, thanks for all the proposals, I used to do this the following way:

    $ echo /home/parent/child1/child2/filename | rev | cut -d '/' -f1 | rev
    filename
    

    Glad to notice there are better manners

    0 讨论(0)
提交回复
热议问题