在bash [duplicate]中提取没有路径和扩展名的文件基名

本文探讨了在Bash中如何从完整文件路径中去除路径和扩展名,仅保留文件基名。提供了多种方法,包括使用内置命令和字符串操作技巧。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

本文翻译自:Extract file basename without path and extension in bash [duplicate]

This question already has an answer here: 这个问题在这里已有答案:

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(例如bashdashksh等)。

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"
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值