Bash 如何替换多个文件名中的一个字符串
我有很多这样的文件Bash 如何替换多个文件名中的一个字符串,bash,Bash,我有很多这样的文件 BBG-06-0645-01B.txt BFDG_06-0219-01T.txt MFD-02-0047-011T.txt BBTF_06-0649-01N.txt BFGD_02-2486-016J.txt 我试图用下划线替换任何连字符,如下所示 BBG_06_0645_01B.txt BFDG_06_0219_01T.txt MFD_02_0047_011T.txt BBTF_06_0649_01N.txt BFGD_02_2486_
BBG-06-0645-01B.txt
BFDG_06-0219-01T.txt
MFD-02-0047-011T.txt
BBTF_06-0649-01N.txt
BFGD_02-2486-016J.txt
我试图用下划线替换任何连字符,如下所示
BBG_06_0645_01B.txt
BFDG_06_0219_01T.txt
MFD_02_0047_011T.txt
BBTF_06_0649_01N.txt
BFGD_02_2486_016J.txt
我试着使用下面的方法,但没有成功
rename -nvs - _ *.txt
Using expression: sub { use feature ':5.18'; s/\Q${\"\-"}/_/ }
'BBG-06-0645-01B.txt' would be renamed to 'BBG_06-0645-01B.txt'
'BBTF_06-0649-01N.txt' would be renamed to 'BBTF_06_0649-01N.txt'
'BFDG_06-0219-01T.txt' would be renamed to 'BFDG_06_0219-01T.txt'
'BFGD_02-2486-016J.txt' would be renamed to 'BFGD_02_2486-016J.txt'
'MFD-02-0047-011T.txt' would be renamed to 'MFD_02-0047-011T.txt'
如果我也使用
rename's/\Q${\“\-”}/\/'*.txt
的话,在这里使用纯BASH替换时,不会将它们全部改为。请尝试以下内容(仅限试运行)
这只会首先打印语句,一旦您对命令(mv
commands)满意,然后从上述命令中删除echo
下面是输出mv BBG-06-0645-01B.txt BBG_06_0645_01B.txt
一旦您对以上结果感到满意,请使用以下方法
for file in *.txt
do
echo "File named $file is going to rename to ${file//-/_}"
mv "$file" "${file//-/_}"
done
如果要打印已成功重命名或未使用的文件的状态:
for file in *.txt
do
echo "File named $file is going to rename to ${file//-/_}"
if mv "$file" "${file//-/_}"
then
echo "File named $file is successfully renamed to ${file//-/_}"
else
echo "Please check seems file $file did not rename."
fi
done
您可以像这样使用
rename
:
rename "s/-/_/g" *.txt
使用-n
标志进行试运行:
rename -n "s/-/_/g" *.txt
用for循环替换bash:
for file in *.txt; do mv "$file" "${file//-/_}" ; done
使用echo
而不是mv
进行试运行:
for file in *.txt; do echo "$file" "${file//-/_}" ; done
它给了我这个
mv BBG-06-0645_01B.txt BBG-06-0645-01B.txt mv BBTF-06-0649-01N.txt mv BFDG-06-0219_01T.txt BFDG-06-0219-01T.txt mv BFGD-02-2486_016J.txt BFGD-02-2486-016J.txt mv-MFD-02-0047_011T.MFD-02-0047-011T.txt我希望所有这些代码都能成为学习者,正如我所说的正确,它将打印将要执行的命令(一旦您从我的代码中删除echo
),验证它们是否对您有利,然后从该代码中删除echo
,它将重命名实际的文件。您的示例与预期相反<代码>$file
应该放在${file/-/}
之前(将其切换过来)。。。您正试图将此_file.txt
重命名为此file.txt
@I'L'I,非常感谢您让我知道输入错误,我现在已修复。非常感谢。请恕我冒犯,因为我看到您为替换添加了tr
,所以我在我的解决方案中添加了BASH替换(这里没有代码副本):)我想在这里提及,以免混淆。注意:如果rename
是由util linux
包提供的(在许多发行版上都是这样)正则表达式不受支持,因为它们与perl rename
@RavinderSingh13一样:我不太清楚您的意思。
for file in *.txt; do echo "$file" "${file//-/_}" ; done