Shell實現(xiàn)批量操作文件的方法詳解
1.文件夾結(jié)構(gòu)
準備如下文件夾結(jié)構(gòu)作為演示:
如E:\Code\Shell有如下文件夾結(jié)構(gòu),有3個相同文件test.txt
2.查找某文件夾下指定文件所在的路徑
find可以查找某個目錄下的指定文件(或目錄)所在的路徑
find 目錄名 -name 文件名
# 查找Shell文件夾下test.txt所在路徑 find Shell -name test.txt
執(zhí)行結(jié)果:
Shell/a/test/test.txt
Shell/b/test/test.txt
Shell/c/test/test.txt
如果不指定目錄名,則是查找當前文件夾下的文件
# 查找當前文件夾下的test.txt所在路徑 find -name test.txt
執(zhí)行結(jié)果:
./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后的文件夾結(jié)構(gòu)如下
4.批量重命名某文件夾下指定的文件名
編寫腳本batch_rename_file.sh,內(nèi)容如下:
# 批量重命名指定文件夾下的文件名或目錄名 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
執(zhí)行腳本,結(jié)果如下:
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后的文件夾結(jié)構(gòu)如下:
5.批量將某文件夾下指定文件移至上級目錄
編寫腳本mv_file_to_upperLevel.sh,內(nèi)容如下:
# 批量將指定文件夾下的文件或目錄,移至上級目錄 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
執(zhí)行腳本,結(jié)果如下:
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至上級目錄后的文件夾結(jié)構(gòu)如下:
到此這篇關(guān)于Shell實現(xiàn)批量操作文件的方法詳解的文章就介紹到這了,更多相關(guān)Shell批量操作文件內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
Linux 下xargs命令詳解及xargs與管道的區(qū)別
在工作中經(jīng)常會接觸到xargs命令,特別是在別人寫的腳本里面也經(jīng)常會遇到,但是卻很容易與管道搞混淆,本篇會詳細講解到底什么是xargs命令,為什么要用xargs命令以及與管道的區(qū)別,本文通過實例給大家詳解,需要的的朋友參考下2017-04-04一天一個shell命令 linux文本內(nèi)容操作系列-grep命令詳解
這篇文章主要介紹了一天一個shell命令 linux文本內(nèi)容操作系列-grep命令詳解 ,需要的朋友可以參考下2016-06-06