在bash中提取文件名,不包含路径和扩展名

从不说:

给定以下文件名:

/the/path/foo.txt
bar.txt

我希望得到:

foo
bar

为什么这不起作用?

#!/bin/bash

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

什么是正确的方法?

ghostdog74:

您不必调用外部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

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章