Linux 批量重命名文件的方法


1.使用rename命令

SYNOPSIS
rename from to file...

from 表示需要替換或者處理的字符,比如文件的擴展名,文件名.

to 表示對from處理之后的結果。

file 表示目標文件。

[root@liujianfan 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

[root@liujianfan tmp]# rename ".log" ".jpg" *
[root@liujianfan 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:

[root@liujianfan 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處理:

[root@liujianfan tmp]# ls|sed -nr "s#(^.*[0-9].)(.*)#mv & \1log#gp"|bash
[root@liujianfan 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再配合替換字符串

[root@liujianfan 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:

[root@liujianfan tmp]# ./rename.sh |bash
[root@liujianfan 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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM