Linux利用sed批量修改文件名

初始文件名

# ls -lh 
total 5.5G
-rw-r--r-- 1 root root 193K Sep 28 09:38 20180908.txt
drwxr-xr-x 2 root root 4.0K Mar  7 16:37 batch
-rw-r--r-- 1 root root 160M Mar 13 16:35 batch_dispatcher.log.1
-rw-r--r-- 1 root root  17M Jan  8 12:00 batch_gen_scheduler.log.1
-rw-r--r-- 1 root root 3.5G Mar 13 16:36 batch_scheduler.log.1
-rw-r--r-- 1 root root 329M Jan 25 10:11 batch_scheduler_test.log.1
drwxr-xr-x 2 root root 4.0K Jan 21 13:54 batch_test
-rw-r--r-- 1 root root  30M Jan 25 10:10 batch_test_dispatcher.log.1
-rw-r--r-- 1 root root 137M Mar 13 16:29 boss_bi_access.log.1
-rw-r--r-- 1 root root  86M Mar 13 16:29 boss_bi_error.log.1
-rw-r--r-- 1 root root 185M Mar 13 14:32 boss_channel_access.log.1
-rw-r--r-- 1 root root  96M Mar 13 14:32 boss_channel_error.log.1
-rw-r--r-- 1 root root  77K Jan 21 14:45 monitor_once.log.1
-rw-r--r-- 1 root root 638M Mar 13 16:35 monitor_scheduler.log.1
-rw-r--r-- 1 root root  26M Dec 10 22:00 yqb_job.log.1
drwxr-xr-x 2 root root 4.0K May 29  2018 zhongcai
-rw-r--r-- 1 root root 348M Mar 13 16:35 zhongcai_scheduler.log.1
-rw-r--r-- 1 root root 688K Jan 28 10:51 zhongcai_test_access.log.1
-rw-r--r-- 1 root root 538K Jan 29 11:23 zhongcai_test_error.log.1
drwxr-xr-x 2 root root 4.0K Aug 21  2018 zhongcai_v1.4

需要将.log.1结尾的文件更改为.log
命令如下:

# for file in $(ls -lh | awk '$NF~/log/{print $NF}');do newfile=$(echo $file | sed 's/\.1//g'); mv $file $newfile; done
# 美化一下
for file in $(ls -lh | awk '$NF~/log/{print $NF}'); do
    newfile=$(echo $file | sed 's/\.1//g')
    mv $file $newfile
done

法二:

#  ls *.1 | sed -r "s#(.*).1#mv & \1#" | bash 

注:
sed替换标记:
\1表示前面第一个左括号所表示的内容,\2表示前面第二个左括号中表示的内容,以此类推
&表示前面匹配到的内容

上一篇:[USACO 2008 MAR] 土地购买


下一篇:20190327 Redis主从同步、三台服务器部署,基于sentinel实现redis主从切换