我知道如何删除文件的扩展名,当我知道它时:
nameis=$(basename $dataset .csv)
Run Code Online (Sandbox Code Playgroud)
但是我想在不事先知道的情况下删除任何扩展名,任何人都知道如何做到这一点?
任何帮助,Ted
Mar*_*air 30
在bash中,您可以执行以下操作:
nameis=${dataset%.*}
Run Code Online (Sandbox Code Playgroud)
......例如:
$ dataset=foo.txt
$ nameis=${dataset%.*}
$ echo $nameis
foo
Run Code Online (Sandbox Code Playgroud)
该语法在bash手册页中描述为:
$ {参数%字}
$ {参数%%词}
删除匹配的后缀模式.这个词被扩展为产生一个模式,就像路径名扩展一样.如果模式匹配参数展开值的尾部,那么展开的结果是具有最短匹配模式("%"情况)或最长匹配模式("%%"情况)的参数的扩展值)删除.如果参数是@或*,则模式删除操作依次应用于每个位置参数,并且扩展是结果列表.如果参数是使用@或*下标的数组变量,则模式删除操作依次应用于数组的每个成员,并且扩展是结果列表.
小智 5
现在,如果你想要一些时尚的老派正则表达式:
echo "foo.bar.tar.gz" | sed "s/^\(.*\)\..*$/\1/"
Run Code Online (Sandbox Code Playgroud)
- >应该返回:foo.bar.tar
I will break it down: s/ Substitute ^ From the beginning \( Mark .* Everything (greedy way) \) Stop Marking (the string marked goes to buffer 1) \. until a "." (which will be the last dot, because of the greedy selection) .* select everything (this is the extension that will be discarded) $ until the end / With (substitute) \1 The buffer 1 marked above (which is the filename before the last dot(.) / End
克里斯蒂亚诺·萨维诺