给定如下文件名:
/the/path/foo.txt
bar.txt
我希望得到:
foo
bar
为什么这样不行?
#!/bin/bash
fullfile=$1
fname=$(basename $fullfile)
fbname=${fname%.*}
echo $fbname
正确的方法是什么?
给定如下文件名:
/the/path/foo.txt
bar.txt
我希望得到:
foo
bar
为什么这样不行?
#!/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}"
foo
$ echo "${s%.*}"
foo
请注意,该解决方案应适用于所有最近(post 2004)POSIX兼容的shell (例如bash
、dash
、ksh
等).
资料来源:Shell Command Language 2.6.2 Parameter Expansion
更多关于bash字符串操作的信息:http://tldp.org/LDP/LG/issue18/bash.html