日本免费高清视频-国产福利视频导航-黄色在线播放国产-天天操天天操天天操天天操|www.shdianci.com

學無先后,達者為師

網站首頁 編程語言 正文

Shell實現批量操作文件的方法詳解_linux shell

作者:將沖破艾迪i ? 更新時間: 2022-11-18 編程語言

1.文件夾結構

準備如下文件夾結構作為演示:

如E:\Code\Shell有如下文件夾結構,有3個相同文件test.txt

2.查找某文件夾下指定文件所在的路徑

find可以查找某個目錄下的指定文件(或目錄)所在的路徑

find 目錄名 -name 文件名
# 查找Shell文件夾下test.txt所在路徑
find Shell -name test.txt

執行結果:

Shell/a/test/test.txt
Shell/b/test/test.txt
Shell/c/test/test.txt

如果不指定目錄名,則是查找當前文件夾下的文件

# 查找當前文件夾下的test.txt所在路徑
find -name test.txt

執行結果:

./Shell/a/test/test.txt
./Shell/b/test/test.txt
./Shell/c/test/test.txt

3.批量刪除某個文件夾下的指定文件

刪除某個目錄下的指定文件(或目錄)

find 目錄名 -name 文件名 |xargs rm -rf
# 刪除Shell文件夾下所有test.txt
find Shell -name test.txt |xargs rm -rf

刪除test.txt后的文件夾結構如下

4.批量重命名某文件夾下指定的文件名

編寫腳本batch_rename_file.sh,內容如下:

# 批量重命名指定文件夾下的文件名或目錄名
oldFileName="test.txt" # 原文件名
newFileName="case.txt" # 新文件名
targetFolder="Shell" # 指定文件夾名

for filePath in  `find $targetFolder -name $oldFileName`
do
    dirPath=`dirname $filePath` # 文件所在目錄
    mv $filePath $dirPath/$newFileName
    echo "$filePath -> $dirPath/$newFileName"
done

執行腳本,結果如下:

Shell/a/test/test.txt -> Shell/a/test/case.txt
Shell/b/test/test.txt -> Shell/b/test/case.txt
Shell/c/test/test.txt -> Shell/c/test/case.txt

重命名test.txt后的文件夾結構如下:

5.批量將某文件夾下指定文件移至上級目錄

編寫腳本mv_file_to_upperLevel.sh,內容如下:

# 批量將指定文件夾下的文件或目錄,移至上級目錄
fileName="test.txt" # 文件名
targetFolder="Shell" # 指定文件夾名

for filePath in  `find $targetFolder -name $fileName`
do
    upperLevelDir=`dirname $(dirname $filePath)` # 上級目錄
    mv $filePath $upperLevelDir
    echo "$filePath -> $upperLevelDir/$fileName"
done

執行腳本,結果如下:

Shell/a/test/test.txt -> Shell/a/test.txt
Shell/b/test/test.txt -> Shell/b/test.txt
Shell/c/test/test.txt -> Shell/c/test.txt

移動test.txt至上級目錄后的文件夾結構如下:

原文鏈接:https://blog.csdn.net/aidijava/article/details/127080413

欄目分類
最近更新