gpt4 book ai didi

bash - 在 Bash 脚本中的文件扩展名之前附加一个字符串

转载 作者:行者123 更新时间:2023-11-29 08:58:48 24 4
gpt4 key购买 nike

我需要使用 Bash 脚本在文件扩展名之前添加一个数字。例如,我想将像 abc.efg 这样的文件名转换为 abc.001.efg。问题是我不知道文件的扩展名是什么(它是脚本的参数之一)。

我一直在寻找最快的方法。

最佳答案

你可以这样做:

extension="${file##*.}"                     # get the extension
filename="${file%.*}" # get the filename
mv "$file" "${filename}001.${extension}" # rename file by moving it

您可以在对 Extract filename and extension in Bash 的出色回答中看到有关这些命令的更多信息.

测试

$ ls hello.*
hello.doc hello.txt

让我们重命名这些文件:

$ for file in hello*; do ext="${file##*.}"; filename="${file%.*}"; mv "$file" "${filename}001.${ext}"; done

现在检查重命名是否按预期进行:

$ ls hello*
hello001.doc hello001.txt

关于bash - 在 Bash 脚本中的文件扩展名之前附加一个字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25122884/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com