在bash中提取没有路径和扩展名的文件基名 [英] Extract file basename without path and extension in bash
本文介绍了在bash中提取没有路径和扩展名的文件基名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
给定如下文件名:
/the/path/foo.txt
bar.txt
我希望得到:
foo
bar
为什么这不起作用?
#!/bin/bash
fullfile=$1
fname=$(basename $fullfile)
fbname=${fname%.*}
echo $fbname
正确的做法是什么?
推荐答案
您不必调用外部 basename
命令.相反,您可以使用以下命令:
You don't have to call the external basename
command. Instead, you could use the following commands:
$ s=/the/path/foo.txt
$ echo "${s##*/}"
foo.txt
$ s=${s##*/}
$ echo "${s%.txt}"
foo
$ echo "${s%.*}"
foo
请注意,此解决方案应适用于所有最近(2004 年之后)POSIX 兼容的 shell,(例如 bash
、dash
、ksh
等).
Note that this solution should work in all recent (post 2004) POSIX compliant shells, (e.g. bash
, dash
, ksh
, etc.).
有关 bash 字符串操作的更多信息:http://tldp.org/LDP/LG/issue18/bash.html
More on bash String Manipulations: http://tldp.org/LDP/LG/issue18/bash.html
这篇关于在bash中提取没有路径和扩展名的文件基名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文