我有几个文本文件并提取一些文件名,如下所示
DFC_2_31A_K14_G008_F2_001D.txt
DFC_2_31A_K66_G005_F1_001D.txt
DFC_2_31A_K66_G005_F2_001D.txt
DFC_2_33_I_K15_G001_F1_001D.txt
DFC_2_33_I_K15_G001_F2_001D.txt
YFC_6_80I_S27_G008_F1_001D.txt
YFC_6_80I_S27_G008_F2_001D.txt
YFC_6_80I_S79_G005_F1_001D.txt
YFC_6_80I_S79_G005_F2_001D.txt
GPC_10_161_A_B_K37_G001_F1_001D.txt
GPC_10_161_A_B_K37_G001_F2_001D.txt
GPC_10_161_A_B_K37_G002_F1_001D.txt
GPC_10_161_A_B_K37_G002_F2_001D.txt
GPC_10_161_A_B_K37_G003_F1_001D.txt
我怎样才能使所有文件名具有相同的模式,如下所示(我希望文件名中有 6 分 \*\_\*\_\*\_\*\_\*\_\*\_001D.txt
)
DFC_2_31A_K14_G008_F2_001D.txt
DFC_2_31A_K66_G005_F1_001D.txt
DFC_2_31A_K66_G005_F2_001D.txt
DFC_2_33I_K15_G001_F1_001D.txt
DFC_2_33I_K15_G001_F2_001D.txt
YFC_6_80I_S27_G008_F1_001D.txt
YFC_6_80I_S27_G008_F2_001D.txt
YFC_6_80I_S79_G005_F1_001D.txt
YFC_6_80I_S79_G005_F2_001D.txt
GPC_10_161AB_K37_G001_F1_001D.txt
GPC_10_161AB_K37_G001_F2_001D.txt
GPC_10_161AB_K37_G002_F1_001D.txt
GPC_10_161AB_K37_G002_F2_001D.txt
GPC_10_161AB_K37_G003_F1_001D.txt
答案1
for file in *_001D.txt; do
if [[ "$file" =~ "A_B" ]]; then
mv "$file" "${file//_A_B/AB}"
fi
if [[ "$file" =~ "_I_K" ]]; then
mv "$file" D"${file/_I_/I_}"
fi
done
在一个简单的循环中迭代所有文件for
,我们首先检查文件名是否具有您要修改的模式。如果存在,我们只需使用mv
参数替换来派生新文件名。它的工作方式是:
对于变量haystack
,语法${haystack/needle/pin}
将找到 的第一个实例needle
,并将其替换为pin
。使用两个/
s (例如${haystack//needle/pin}
)将替换全部这样的例子不仅仅是第一个。