Linux 批量重新命名檔案的方法
阿新 • • 發佈:2018-11-04
1.使用rename命令
SYNOPSIS
rename from to file...
from 表示需要替換或者處理的字元,比如檔案的副檔名,檔名.
to 表示對from處理之後的結果。
file 表示目標檔案。
[[email protected] tmp]# ls hello_10_2016-03-17.log hello_4_2016-03-17.log hello_8_2016-03-17.log hello_1_2016-03-17.log hello_5_2016-03-17.log hello_9_2016-03-17.log hello_2_2016-03-17.log hello_6_2016-03-17.log hello_3_2016-03-17.log hello_7_2016-03-17.log
使用rename將.log改為.jpg
[[email protected] tmp]# rename ".log" ".jpg" * [[email protected] tmp]# ls hello_10_2016-03-17.jpg hello_4_2016-03-17.jpg hello_8_2016-03-17.jpg hello_1_2016-03-17.jpg hello_5_2016-03-17.jpg hello_9_2016-03-17.jpg hello_2_2016-03-17.jpg hello_6_2016-03-17.jpg hello_3_2016-03-17.jpg hello_7_2016-03-17.jpg
2.使用sed:
[[email protected] tmp]# ls|sed -nr "s#(^.*[0-9].)(.*)#mv & \1log#gp" mv hello_10_2016-03-17.jpg hello_10_2016-03-17.log mv hello_1_2016-03-17.jpg hello_1_2016-03-17.log mv hello_2_2016-03-17.jpg hello_2_2016-03-17.log mv hello_3_2016-03-17.jpg hello_3_2016-03-17.log mv hello_4_2016-03-17.jpg hello_4_2016-03-17.log mv hello_5_2016-03-17.jpg hello_5_2016-03-17.log mv hello_6_2016-03-17.jpg hello_6_2016-03-17.log mv hello_7_2016-03-17.jpg hello_7_2016-03-17.log mv hello_8_2016-03-17.jpg hello_8_2016-03-17.log mv hello_9_2016-03-17.jpg hello_9_2016-03-17.log
最後通過管道給bash處理:
[[email protected] tmp]# ls|sed -nr "s#(^.*[0-9].)(.*)#mv & \1log#gp"|bash
[[email protected] tmp]# ls
hello_10_2016-03-17.log hello_4_2016-03-17.log hello_8_2016-03-17.log
hello_1_2016-03-17.log hello_5_2016-03-17.log hello_9_2016-03-17.log
hello_2_2016-03-17.log hello_6_2016-03-17.log
hello_3_2016-03-17.log hello_7_2016-03-17.log
3.使用for再配合替換字串
[[email protected] tmp]# vim rename.sh
#!/bin/bash
#This script is use to rename files
for name in `ls *.log`;
do
echo "mv $name ${name/.log/.txt}"
done
最後通過bash:
[[email protected] tmp]# ./rename.sh |bash
[[email protected] tmp]# ls
hello_10_2016-03-17.txt hello_4_2016-03-17.txt hello_8_2016-03-17.txt
hello_1_2016-03-17.txt hello_5_2016-03-17.txt hello_9_2016-03-17.txt
hello_2_2016-03-17.txt hello_6_2016-03-17.txt rename.sh
hello_3_2016-03-17.txt hello_7_2016-03-17.txt