利用sed构造命令批量处理文件
前言
最优解决方案未必是第一时间能想到的思路。在处理工作中偶尔涉及的临时脚本时,无需过分追求代码的健壮性,核心目标应是提升编写效率。此处分享一种借助sed命令构建指令来应对批量文件处理的实用方法,供读者参考借鉴。
需求案例1
假设当前目录下存在数十个类似0_80_91.txt、0_80_92.txt、0_80_93.txt的文件,需要将其中所有文件名内的“80”替换为“81”,即实现从0_80_XX.txt到0_81_XX.txt的批量更名。
具体的实现命令如下:ls *.txt |sed -nr 's/(0_)(80)(.*)/mv \1\2\3 \181\3/gp' | sh
#ls *.txt
0_80_91.txt 0_80_92.txt 0_80_93.txt
#ls *.txt |sed -nr 's/(0_)(80)(.*)/mv \1\2\3 \181\3/gp'
mv 0_80_91.txt 0_81_91.txt
mv 0_80_92.txt 0_81_92.txt
mv 0_80_93.txt 0_81_93.txt
#ls *.txt |sed -nr 's/(0_)(80)(.*)/mv \1\2\3 \181\3/gp' | sh
#ls *.txt
0_81_91.txt 0_81_92.txt 0_81_93.txt
需求案例2
若需将当前目录下所有的0_80_91.Z、0_80_92.Z、0_80_93.Z等文件通过cc_uncompress工具进行解压,并指定输出文件路径,调用格式通常为cc_uncompress -s 源文件名 -d 目标文件名。其中目标文件名可自定义,例如设为1.txt或其他任意名称。
第一种实现方式命令为:ls *.Z | sed -nr 's/(.*)/cc_uncompress -s \1 -d \1.txt/gp'
#ls *.Z | sed -nr 's/(.*)/cc_uncompress -s \1 -d \1.txt/gp'
cc_uncompress -s 0_80_91.Z -d 0_80_91.Z.txt
cc_uncompress -s 0_80_92.Z -d 0_80_92.Z.txt
cc_uncompress -s 0_80_93.Z -d 0_80_93.Z.txt
#ls *.Z | sed -nr 's/(.*)/cc_uncompress -s \1 -d \1.txt/gp' | sh
第二种实现方式命令为:find . -name "*.Z" -exec cc_uncompress -s {} -d {}.bak \;
以上即为本文的全部内容,希望能对各位的学习与工作有所帮助,同时也欢迎大家继续支持本站。