解压缩文件名和扩展名中的Bash [英] Extract filename and extension in Bash

查看:111
本文介绍了解压缩文件名和扩展名中的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 会考虑 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)

但我preFER不火只为这一个Python间preTER,如果可能的话。

but I'd prefer not to fire a Python interpreter just for this, if possible.

任何更好的想法?

推荐答案

首先,获取文件名,不带路径:

First, get file name without the path:

filename=$(basename "$fullfile")
extension="${filename##*.}"
filename="${filename%.*}"

另外,你可以专注于最后的路径,而不是的'。''/'这应该工作,即使你有未predictable文件扩展名:

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##*/}"

这篇关于解压缩文件名和扩展名中的Bash的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆