[Shell] Batch operation files: find file paths, delete files in batches, rename files in batches, move files to parent directories in batches

1. Folder structure

Prepare the following folder structure as a demonstration:
If there isE:\Code\Shell the following folder structure, there are 3 identical filestest.txt

insert image description here

2. Find the path where the specified file is located in a folder

findYou can find the path where the specified file (or directory) in a certain directory is located

# 查找Shell文件夹下test.txt所在路径
$ find Shell -name test.txt
Shell/a/test/test.txt
Shell/b/test/test.txt
Shell/c/test/test.txt

If you do not specify a directory name, it is to find the files in the current folder

# 查找当前文件夹下的test.txt所在路径
$ find -name test.txt
./Shell/a/test/test.txt
./Shell/b/test/test.txt
./Shell/c/test/test.txt

3. Delete specified files in a folder in batches

To delete a specified file (or directory) in a certain directory, you only need to add it after the find command |xargs rm -rf.

# 删除Shell文件夹下所有test.txt
find Shell -name test.txt |xargs rm -rf

The folder structure after deleting test.txt is as follows:

insert image description here

4. Batch rename the specified file name under a certain folder

Write a script batch_rename_file.shwith the following content:

# 批量重命名指定文件夹下的文件名或目录名
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

Execute the script, the result is as follows:

$ sh batch_rename_file.sh
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

The folder structure after renaming test.txt is as follows:

insert image description here

5. Batch move the specified files under a certain folder to the parent directory

Write a script mv_file_to_upperLevel.shwith the following content:

# 批量将指定文件夹下的文件或目录,移至上级目录
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

Execute the script, the result is as follows:

$ sh mv_file_to_upperLevel.sh
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

The folder structure after moving test.txt to the parent directory is as follows:

insert image description here

Guess you like

Origin blog.csdn.net/aidijava/article/details/127080413