在bash中提取不带路径和扩展名的文件basename[重复]

这个问题在这里已经有答案了
在Bash中提取文件名和扩展名

(37个答案)

五年前关闭的

给定如下文件名:

/the/path/foo.txt
bar.txt

我希望得到:

foo
酒吧

为什么这不起作用

#/bin/bash
fullfile=$1
fname=$(basename$fullfile)
fbname=${fname%.*}
echo$fbname

正确的方法是什么

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

$s=/the/path/foo.txt
$echo“${s##*/}”
foo.txt
$s=${s###*/}
$echo“${s%.txt}”
福
$echo“${s%.*}”
福

请注意,此解决方案应适用于所有最近的(2004年之后的POSIX兼容shell(例如bashdashksh等)

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

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

发表评论