Grab the filename in Unix out of full path

2019-02-05 12:13发布

I am trying to get "abc.txt" out of /this/is/could/be/any/path/abc.txt using Unix command. Note that /this/is/could/be/any/path is dynamic.

Any idea?

Thanks in advance.

4条回答
Animai°情兽
2楼-- · 2019-02-05 12:21

In bash:

path=/this/is/could/be/any/path/abc.txt

If your path has spaces in it, wrap it in "

path="/this/is/could/be/any/path/a b c.txt"

Then to extract the path, use the basename function

file=$(basename "$path")

or

file=${path##*/}
查看更多
We Are One
3楼-- · 2019-02-05 12:35

basename path gives the file name at the end of path

Edit:

It is probably worth adding that a common pattern is to use back quotes around commands e.g. `basename ...`, so UNIX shells will execute the command and return its textual value.

So to assign the result of basename to a variable, use

x=`basename ...path...`

and $x will be the file name.

查看更多
女痞
4楼-- · 2019-02-05 12:35

You can use dirname command

$ dirname $path
查看更多
Anthone
5楼-- · 2019-02-05 12:38

You can use basename /this/is/could/be/any/path/abc.txt

查看更多
登录 后发表回答