在 Bash 中提取文件名和扩展名 [英] Extract filename and extension in Bash
问题描述
我想分别获取文件名(不带扩展名)和扩展名.
I want to get the filename (without extension) and the extension separately.
目前我找到的最佳解决方案是:
The best solution I found so far is:
NAME=`echo "$FILE" | cut -d'.' -f1`
EXTENSION=`echo "$FILE" | cut -d'.' -f2`
这是错误的,因为如果文件名包含多个 .
字符,则它不起作用.如果,比方说,我有 abjs
,它会考虑 a
和 b.js
,而不是 ab
和 js
.
This is wrong because it doesn't work if the file name contains multiple .
characters. If, let's say, I have a.b.js
, it will consider a
and b.js
, instead of a.b
and js
.
它可以在 Python 中轻松完成
It can be easily done in Python with
file, ext = os.path.splitext(path)
但如果可能的话,我不想为此启动 Python 解释器.
but I'd prefer not to fire up a Python interpreter just for this, if possible.
有更好的想法吗?
推荐答案
首先获取不带路径的文件名:
First, get file name without the path:
filename=$(basename -- "$fullfile")
extension="${filename##*.}"
filename="${filename%.*}"
或者,您可以关注路径的最后一个/"而不是."即使您有不可预测的文件扩展名,这也应该有效:
Alternatively, you can focus on the last '/' of the path instead of the '.' which should work even if you have unpredictable file extensions:
filename="${fullfile##*/}"
您可能需要查看文档:
- 在网络部分3.5.3 Shell参数扩展"
- 在 bash 手册页中名为参数扩展"的部分
这篇关于在 Bash 中提取文件名和扩展名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!