我试图在移动过程中用sed替换部分文件名。我想要的是在转移操作之后明确表示某个文件从“READY”变为“SENT”:
假设有两个文件(至少),出于测试目的,我用触摸生成:
>touch READY01_file_to_process.txt
>touch READY02_file_to_process.txt
然后我试着这样做:
>ls READY* | xargs -I% mv "%" $(echo "%" | sed 's/READY/SENT/')
但它没有按预期工作。只是为了调试它我把'mv'变成'echo'就像这样:
>ls READY* | xargs -I% echo "%" $(echo "%" | sed 's/READY/SENT/')
我期待看到这个输出:
READY01_file_to_process.txt SENT01_file_to_process.txt
READY02_file_to_process.txt SENT02_file_to_process.txt
但是它给出了以下内容(根本没有替换):
READY01_file_to_process.txt READY01_file_to_process.txt
READY02_file_to_process.txt READY02_file_to_process.txt
我很确定这是一些我觉得无法发现的蠢事...... 提前谢谢。
答案 0 :(得分:1)
不要parse ls并且还有其他方法可以重命名文件
1)如果您的rename
命令不基于perl
,请执行以下操作:http://man7.org/linux/man-pages/man1/rename.1.html
$ touch READY0{1,2}_file_to_process.txt
$ # -v is for verbose output
$ # note how same glob is used as what you used with ls
$ rename -v READY SENT READY*
`READY01_file_to_process.txt' -> `SENT01_file_to_process.txt'
`READY02_file_to_process.txt' -> `SENT02_file_to_process.txt'
2)如果你有perl
rename
$ # -n is for dry run, remove and run cmd again after it looks okay
$ rename -n 's/READY/SENT/' READY*
rename(READY01_file_to_process.txt, SENT01_file_to_process.txt)
rename(READY02_file_to_process.txt, SENT02_file_to_process.txt)
3)for-loop和http://mywiki.wooledge.org/BashGuide/Parameters#Parameter_Expansion
$ # remove echo once it looks okay
$ for f in READY*; do echo mv "$f" "${f/READY/SENT}"; done
mv READY01_file_to_process.txt SENT01_file_to_process.txt
mv READY02_file_to_process.txt SENT02_file_to_process.txt