我需要在文件名匹配的文件名之间添加字符串。
示例文件名:
file_1_my001
file_11_my0012
file_65_my_012
我想将它们重命名为:
file_1_my_copied_001
file_11_my_copied_0012
file_65_my_copied_012
模式为<any string>0<any string>
我的逻辑是首先获取以0开头的数字格式,将变量存储为模式,然后搜索变量并将其替换为_copied_<variable>
。我尝试将数字取为:
ls | sed -e s/[^0-9]//g
但是上面的命令是获取文件名中的所有数字,例如。 1001, 110012, 65012
我无法搜索从0开始的数字格式。请指导。
答案 0 :(得分:1)
使用基于perl
的{{1}}命令:
rename
$ touch file_1_my001 file_11_my0012 file_65_my_012
$ rename -n 's/_?(?=0)/_copied_/' file_*
rename(file_11_my0012, file_11_my_copied_0012)
rename(file_1_my001, file_1_my_copied_001)
rename(file_65_my_012, file_65_my_copied_012)
零个或一个_?(?=0)
后跟_
0
选项适用于干运行,看起来不错后,请删除实际重命名选项
如果-n
基于perl
不可用,请尝试:
rename
如果可以,请将$ for file in file_* ; do echo mv "$file" $(echo "$file" | sed 's/_\?0/_copied_0/'); done
mv file_11_my0012 file_11_my_copied_0012
mv file_1_my001 file_1_my_copied_001
mv file_65_my_012 file_65_my_copied_012
更改为echo mv
以进行实际重命名
如果mv
之前的选项_
不存在,则更容易使用parameter expansion
0
答案 1 :(得分:0)
ls | sed -e 's/\([_]*0\)/_copied_0/'
答案 2 :(得分:0)
类似的东西,
$ sed -E "s/(.*[^0-9]+)(0[0-9]*)/\1_copied_\2/"