本文翻译自:Extract file basename without path and extension in bash [duplicate]
This question already has an answer here: 这个问题在这里已有答案:
- Extract filename and extension in Bash 37 answers 在Bash 37答案中 提取文件名和扩展名
Given file names like these: 给定这样的文件名:
/the/path/foo.txt
bar.txt
I hope to get: 我希望得到:
foo
bar
Why this doesn't work? 为什么这不起作用?
#!/bin/bash
fullfile=$1
fname=$(basename $fullfile)
fbname=${fname%.*}
echo $fbname
What's the right way to do it? 什么是正确的方法呢?
#1楼
参考:https://stackoom.com/question/BBDg/在bash-duplicate-中提取没有路径和扩展名的文件基名
#2楼
Use the basename command. 使用basename命令。 Its manpage is here: http://unixhelp.ed.ac.uk/CGI/man-cgi?basename 它的联机帮助页面在这里: http : //unixhelp.ed.ac.uk/CGI/man-cgi?basename
#3楼
Here is another (more complex) way of getting either the filename or extension, first use the rev
command to invert the file path, cut from the first .
这是获取文件名或扩展名的另一种(更复杂的)方法,首先使用rev
命令反转文件路径,从第一个开始剪切.
and then invert the file path again, like this: 然后再次反转文件路径,如下所示:
filename=`rev <<< "$1" | cut -d"." -f2- | rev`
fileext=`rev <<< "$1" | cut -d"." -f1 | rev`
#4楼
If you want to play nice with Windows file paths (under Cygwin) you can also try this: 如果你想玩Windows文件路径(在Cygwin下),你也可以试试这个:
fname=${fullfile##*[/|\\]}
This will account for backslash separators when using BaSH on Windows. 这将在Windows上使用BaSH时考虑反斜杠分隔符。
#5楼
You don't have to call the external basename
command. 您不必调用外部basename
命令。 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
Note that this solution should work in all recent ( post 2004 ) POSIX compliant shells, (eg bash
, dash
, ksh
, etc.). 请注意,此解决方案应适用于所有最近( 2004年后 ) POSIX兼容的shell(例如bash
, dash
, ksh
等)。
Source: Shell Command Language 2.6.2 Parameter Expansion 来源: Shell命令语言2.6.2参数扩展
More on bash String Manipulations: http://tldp.org/LDP/LG/issue18/bash.html 有关bash String Manipulations的更多信息: http : //tldp.org/LDP/LG/issue18/bash.html
#6楼
The basename command has two different invocations; basename命令有两个不同的调用; in one, you specify just the path, in which case it gives you the last component, while in the other you also give a suffix that it will remove. 在一个中,您只指定路径,在这种情况下,它会为您提供最后一个组件,而在另一个中,您还会提供一个将删除的后缀。 So, you can simplify your example code by using the second invocation of basename. 因此,您可以使用basename的第二次调用来简化示例代码。 Also, be careful to correctly quote things: 另外,要小心正确引用事物:
fbname=$(basename "$1" .txt) echo "$fbname"