bash 在bash脚本中的文件扩展名之前附加一个字符串
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/25122884/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Appending a string before file extension in bash script
提问by kMaster
I need to add a number just before the extension of the files in a bash script. For example, I want to convert a file name name like "abc.efg
" to "abc.001.efg
. The problem is that I don't know what is the extension of the file (it is one of the parameters of the script).
我需要在 bash 脚本中的文件扩展名之前添加一个数字。比如我想把一个像“ abc.efg
”这样的文件名转换成“ ”,abc.001.efg
问题是我不知道文件的扩展名是什么(它是脚本的参数之一)。
I was looking for the quickest way of doing this.
我正在寻找这样做的最快方法。
Thanks in advance,
提前致谢,
回答by fedorqui 'SO stop harming'
You can do something like this:
你可以这样做:
extension="${file##*.}" # get the extension
filename="${file%.*}" # get the filename
mv "$file" "${filename}001.${extension}" # rename file by moving it
You can see more info about these commands in the excellent answer to Extract filename and extension in bash.
您可以在Extract filename and extension in bash的优秀答案中查看有关这些命令的更多信息。
Test
测试
$ ls hello.*
hello.doc hello.txt
Let's rename these files:
让我们重命名这些文件:
$ for file in hello*; do ext="${file##*.}"; filename="${file%.*}"; mv "$file" "${filename}001.${ext}"; done
Tachan...
塔坎...
$ ls hello*
hello001.doc hello001.txt
回答by Kent
sed 's/\.[^.]*$/.001&/'
you can build your mv
cmd with above one-liner.
您可以mv
使用上面的单行构建您的cmd。
example:
例子:
kent$ echo "abc.bar.blah.hello.foo"|sed 's/\.[^.]*$/.001&/'
abc.bar.blah.hello.001.foo
回答by Greg Reynolds
If your file extension is in a variable EXT, and your file is in a variable FILE, then something like this should work
如果您的文件扩展名在一个变量 EXT 中,而您的文件在一个变量 FILE 中,那么这样的事情应该可以工作
EXT=ext;FILE=file.ext;echo ${FILE/%$EXT/001.$EXT}
This prints
这打印
file.001.ext
The substitution is anchored to the end of the string, so it won't matter if your extension appears in the filename. More info here http://tldp.org/LDP/abs/html/string-manipulation.html
替换固定在字符串的末尾,因此扩展名是否出现在文件名中无关紧要。更多信息在这里http://tldp.org/LDP/abs/html/string-manipulation.html