Extract directory path and filename

后端 未结 7 984
遇见更好的自我
遇见更好的自我 2021-01-31 03:06

I have a variable which has the directory path, along with the file name. I want to extract the filename alone from the Unix directory path and store it in a variable.



        
7条回答
  •  半阙折子戏
    2021-01-31 03:26

    Using bash "here string":

    $ fspec="/exp/home1/abc.txt" 
    $ tr  "/"  "\n"  <<< $fspec | tail -1
    abc.txt
    $ filename=$(tr  "/"  "\n"  <<< $fspec | tail -1)
    $ echo $filename
    abc.txt
    

    The benefit of the "here string" is that it avoids the need/overhead of running an echo command. In other words, the "here string" is internal to the shell. That is:

    $ tr <<< $fspec
    

    as opposed to:

    $ echo $fspec | tr
    

提交回复
热议问题