linux下的批處理建立、重新命名、刪除檔案
阿新 • • 發佈:2019-02-04
今天的內容主要為:批量建立檔案,批量重新命名檔案,批量刪除檔案。
主要通過迴圈操作來實現批量這個功能。
基本知識點:新建檔案,刪除檔案和重新命名檔案的命令:touch,rm,mv,
案例:
- #! /bin/bash
- echo "-----------------the starting line of shell-----------------"
- # create new files
- for name in Test{1..3}.h
- do
- touch $name
- done
- #show the files, which is created
- for name in *.h
- do
- echo $name
- done
- #rename the files
- i=0
- for name in *.h
- do
- newname=${name%.*}-$i
- mv "$name""$newname.h"
- let i++
- done
- #show the new files, which is renamed
- for name in *.h
- do
- echo $name
- done
- #remove the files
- for name in *.h
- do
- rm -rf $name
- done
- echo "-----------------the ending line of shell-----------------"
在終端中執行該程式可以得到以下的結果:
-----------------the starting line of shell-----------------
Test1.h
Test2.h
Test3.h
Test1-0.h
Test2-1.h
Test3-2.h
-----------------the ending line of shell-----------------
通過for迴圈操作實現了批量功能。該指令碼檔案會在指令碼檔案所在的目錄中新建立檔案,也可以把它放到自己定義的目錄執行。該指令碼中沒有指定專門的目錄,在顯示檔案的時候,也是會遍歷指令碼所在目錄中的.h檔案,所以會把指令碼第一階段建立的.h檔案顯示出來。該方法在重新命名和刪除檔案時候也在使用。
另外:在重新命名的時候,name%.*表示把變數值中.前面的內容提取出來。.後面是*表示匹配。例如:name的值是test1.h.經過提取後會得到test1,.h被捨棄。
還有一種方法:name#*.它表示把變數值中.後面的內容提取出來。例如:name的值是test1.h.經過提取後會得到h,test1.會被捨棄。該方法在提取檔名,或者檔案字尾時很有用。