在bash脚本中的文件扩展名之前附加一个字符串 [英] Appending a string before file extension in bash script
本文介绍了在bash脚本中的文件扩展名之前附加一个字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我需要在bash脚本中的文件扩展名前添加一个数字.例如,我想将文件名" abc.efg
"转换为" abc.001.efg
",问题是我不知道它是什么.文件的扩展名(它是脚本的参数之一).
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).
我一直在寻找最快的方法.
I was looking for the quickest way of doing this.
预先感谢
推荐答案
您可以执行以下操作:
extension="${file##*.}" # get the extension
filename="${file%.*}" # get the filename
mv "$file" "${filename}001.${extension}" # rename file by moving it
您可以在在bash中提取文件名和扩展名的绝佳答案中查看有关这些命令的更多信息.
You can see more info about these commands in the excellent answer to Extract filename and extension in bash.
$ 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
塔尚...
$ ls hello*
hello001.doc hello001.txt
这篇关于在bash脚本中的文件扩展名之前附加一个字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文