1、怎麼在linux下修改以某一字母開頭的文件後戳
源文件內容
[root@localhost test]# ls stu10.txt.php stu3.txt.php stu6.txt.php stu9.txt.php test3.txt stu1.txt.php stu4.txt.php stu7.txt.php test1.txt test4.txt stu2.txt.php stu5.txt.php stu8.txt.php test2.txt test5.txt
現在我們將以s開頭的所有文件的後戳修改爲.html
第一步:先將以s開頭的文件找出來
[root@localhost test]# find -type f -name "s*" ./stu8.txt.php ./stu7.txt.php ./stu6.txt.php ./stu9.txt.php ./stu3.txt.php ./stu4.txt.php ./stu2.txt.php ./stu5.txt.php ./stu1.txt.php ./stu10.txt.php
第二步:取文件的前半部分
[root@localhost test]# find -type f -name "s*"|awk -F"[./]+" '{print $2}' stu8 stu7 stu6 stu9 stu3 stu4 stu2 stu5 stu1 stu10
第三步:使用拼接的方法來實現文件後戳的修改
[root@localhost test]# find -type f -name "s*"|awk -F"[./]+" '{print "mv "$2".txt.php "$2".html"}' mv stu8.txt.php stu8.html mv stu7.txt.php stu7.html mv stu6.txt.php stu6.html mv stu9.txt.php stu9.html mv stu3.txt.php stu3.html mv stu4.txt.php stu4.html mv stu2.txt.php stu2.html mv stu5.txt.php stu5.html mv stu1.txt.php stu1.html mv stu10.txt.php stu10.html
第四步:將拼接的內容交給bash來處理
[root@localhost test]# find -type f -name "s*"|awk -F"[./]+" '{print "mv "$2".txt.php "$2".html"}'|bash
第五步:查看修改後的內容
[root@localhost test]# ll total 0 -rw-r--r--. 1 root root 0 Jul 22 11:47 stu10.html -rw-r--r--. 1 root root 0 Jul 22 11:47 stu1.html -rw-r--r--. 1 root root 0 Jul 22 11:47 stu2.html -rw-r--r--. 1 root root 0 Jul 22 11:47 stu3.html -rw-r--r--. 1 root root 0 Jul 22 11:47 stu4.html -rw-r--r--. 1 root root 0 Jul 22 11:47 stu5.html -rw-r--r--. 1 root root 0 Jul 22 11:47 stu6.html -rw-r--r--. 1 root root 0 Jul 22 11:47 stu7.html -rw-r--r--. 1 root root 0 Jul 22 11:47 stu8.html -rw-r--r--. 1 root root 0 Jul 22 11:47 stu9.html -rw-r--r--. 1 root root 0 Jul 22 11:41 test1.txt -rw-r--r--. 1 root root 0 Jul 22 11:41 test2.txt -rw-r--r--. 1 root root 0 Jul 22 11:41 test3.txt -rw-r--r--. 1 root root 0 Jul 22 11:41 test4.txt -rw-r--r--. 1 root root 0 Jul 22 11:41 test5.txt
可以看到已經將所有以s開頭的文件名後戳全部修改爲.html
2、以上修改文件後戳的方法還可以使用腳本來實現
腳本內容如下
#!/bin/bash workDir=/server/file/test 將目錄定義爲一個變量 if [ -d $workDir ];then 判斷目錄是否存在,存在則進入,不存在則推出 cd $workDir else exit 1 fi for i in $(find -type f -name "[s]*") 用for循環來查找以s開頭的文件 do char=`echo $i|awk -F"[/.]+" '{print $2}'` 定義要修改的文件前半部分 mv $i ${char}.html 將文件修改爲想要的內容 done