bash 从完整路径中获取 Unix 中的文件名

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10124314/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 21:56:11  来源:igfitidea点击:

Grab the filename in Unix out of full path

bashshellunixksh

提问by iwan

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

我试图"abc.txt"摆脱/this/is/could/be/any/path/abc.txt使用 Unix 命令。请注意,这/this/is/could/be/any/path是动态的。

Any idea?

任何的想法?

回答by kev

In bash:

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

然后提取路径,使用basename 函数

file=$(basename "$path")

or

或者

file=${path##*/}

回答by gbulmer

basename pathgives the file name at the end of path

basename 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.

可能值得补充的是,一个常见的模式是在命令周围使用反引号,例如 `basename ...`,因此 UNIX shell 将执行命令并返回其文本值。

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

因此,要将 basename 的结果分配给变量,请使用

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

and $x will be the file name.

$x 将是文件名。

回答by Pavel Dolinin

You can use dirname command

您可以使用 dirname 命令

$ dirname $path

回答by tonymarschall

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

您可以使用 basename /this/is/could/be/any/path/abc.txt