Get last field using awk substr

前端 未结 8 493
天涯浪人
天涯浪人 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:56

    Use the fact that awk splits the lines in fields based on a field separator, that you can define. Hence, defining the field separator to / you can say:

    awk -F "/" '{print $NF}' input
    

    as NF refers to the number of fields of the current record, printing $NF means printing the last one.

    So given a file like this:

    /home/parent/child1/child2/child3/filename
    /home/parent/child1/child2/filename
    /home/parent/child1/filename
    

    This would be the output:

    $ awk -F"/" '{print $NF}' file
    filename
    filename
    filename
    
    0 讨论(0)
  • 2020-11-29 02:58

    Another option is to use bash parameter substitution.

    $ foo="/home/parent/child/filename"
    $ echo ${foo##*/}
    filename
    $ foo="/home/parent/child/child2/filename"
    $ echo ${foo##*/}
    filename
    
    0 讨论(0)
提交回复
热议问题