参见英文答案 > Extract filename and extension in Bash 37个
给定这样的文件名:
/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
请注意,此解决方案应适用于所有最近(2004年后)POSIX兼容的shell(例如bash,dash,ksh等).
资料来源:Shell Command Language 2.6.2 Parameter Expansion
有关bash String Manipulations的更多信息:http://tldp.org/LDP/LG/issue18/bash.html
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。