如果参数是文件,我想将它们的扩展名更改为 .file
.
这就是我得到的:
#!/bin/bash
while [ $# -gt 0 ]
do
if [ -f $1 ]
then
sed -i -e "s/\(.*\)\(\.\)\(.*\)/\1\2file" $1
fi
shift
done
脚本正在运行,但没有执行任何操作。另一个问题是该文件没有任何扩展名,我的 sed 命令将不起作用,对吗?请帮忙。
最佳答案
sed 用于操作文件内容,而不是文件名本身。
选项 1,取自 this answer by John Smith :
filename="file.ext1" mv "${filename}" "${filename/%ext1/ext2}"
选项 2,取自 this answer by chooban :
rename 's/\.ext/\.newext/' ./*.ext
选项 3,取自 this answer by David W. :
$ find . -name "*.ext1" -print0 | while read -d $'\0' file do mv $file "${file%.*}.ext2" done
还有here .
更新:(在评论中询问 % 和 {} 在做什么?)
"${variable}other_chars"> 如果你想扩展字符串中的变量,你可以使用它。 {}
中的 %.*
表示将变量的值从值尾部的模式 .*
中取出,例如,如果您的变量为 filename.txt
"${variable%.*} 仅返回 filename
。
关于regex - 使用 sed 更改文件扩展名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44620236/