小编典典

在bash中提取不带路径和扩展名的文件基本名称

linux

给定以下文件名:

/the/path/foo.txt
bar.txt

我希望得到:

foo
bar

为什么这不起作用?

#!/bin/bash

fullfile=$1
fname=$(basename $fullfile)
fbname=${fname%.*}
echo $fbname

什么是正确的方法?


阅读 376

收藏
2020-06-02

共1个答案

小编典典

您不必调用外部basename命令。相反,您可以使用以下命令:

$ s=/the/path/foo.txt
$ echo "${s##*/}"
foo.txt
$ s=${s##*/}
$ echo "${s%.txt}"
foo
$ echo "${s%.*}"
foo

请注意,这个解决方案应该在所有近期的(工作 后2004年POSIX 兼容的外壳(例如bashdashksh等)。

来源:Shell命令语言2.6.2参数扩展

有关bash字符串操作的更多信息:http :
//tldp.org/LDP/LG/issue18/bash.html

2020-06-02