问题描述
如何只获取没有扩展名和路径的文件名?
How would I get just the filename without the extension and no path?
以下没有给我扩展名,但我仍然附上了路径:
The following gives me no extension, but I still have the path attached:
source_file_filename_no_ext=${source_file%.*}
推荐答案
大多数类 UNIX 操作系统都有一个 basename
可执行文件,用于非常相似的目的(以及 dirname
用于路径):
Most UNIX-like operating systems have a basename
executable for a very similar purpose (and dirname
for the path):
pax> a=/tmp/file.txt
pax> b=$(basename $a)
pax> echo $b
file.txt
不幸的是,这只是给了你文件名,包括扩展名,所以你需要找到一种方法来去掉它.
That unfortunately just gives you the file name, including the extension, so you'd need to find a way to strip that off as well.
因此,既然您无论如何都必须这样做,那么您不妨找到一种可以去除路径和扩展名的方法.
So, given you have to do that anyway, you may as well find a method that can strip off the path and the extension.
一种方法(这是一个 bash
-only 解决方案,不需要其他可执行文件):
One way to do that (and this is a bash
-only solution, needing no other executables):
pax> a=/tmp/xx/file.tar.gz
pax> xpath=${a%/*}
pax> xbase=${a##*/}
pax> xfext=${xbase##*.}
pax> xpref=${xbase%.*}
pax> echo;echo path=${xpath};echo pref=${xpref};echo ext=${xfext}
path=/tmp/xx
pref=file.tar
ext=gz
那个小片段设置了 xpath
(文件路径)、xpref
(文件前缀,你特别要求的)和 xfext
(文件扩展名).
That little snippet sets xpath
(the file path), xpref
(the file prefix, what you were specifically asking for) and xfext
(the file extension).
这篇关于仅从 Bash 脚本中的路径获取文件名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!