首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >递归bash脚本,在Mac/Linux上用特定规则重命名文件和文件夹

递归bash脚本,在Mac/Linux上用特定规则重命名文件和文件夹
EN

Stack Overflow用户
提问于 2020-08-07 07:15:44
回答 1查看 597关注 0票数 1

希望你们一切都好!

我是在完成这个相对简单的任务,但我没有得到最佳的结果,所以我需要你的帮助。

设想情况:

我有以下文件和文件夹(目录)结构:

代码语言:javascript
复制
.
├── nested-test-folder-1
│   ├── nested\ test\ file\ 1.txt
│   ├── nested\ test\ file\ 2\ tag1.txt
│   ├── nested\ test\ file\ 3\ tag3.txt
│   └── nested\ test\ file\ 4\ tag2.txt
├── nested-test-folder-2-tag1
│   ├── nested\ test\ file\ 5.txt
│   ├── nested\ test\ file\ 6\ tag1.txt
│   ├── nested\ test\ file\ 7\ tag3.txt
│   └── nested\ test\ file\ 8\ tag2.txt
├── nested-test-folder-3\ tag3
│   ├── nested\ test\ file\ 10\ tag1.txt
│   ├── nested\ test\ file\ 11\ tag3.txt
│   ├── nested\ test\ file\ 12\ tag2.txt
│   └── nested\ test\ file\ 9.txt
├── test\ file\ 13.txt
├── test\ file\ 14\ tag1.txt
├── test\ file\ 15\ tag3.txt
└── test\ file\ 16\ tag2.txt

我试图编写一个递归bash脚本来相应地重命名文件和文件夹:

-如果文件/文件夹包含"tag1“或"tag2”,则将其替换为新的"tag3".

-如果文件/文件夹不包含"tag1“或"tag2”,并且不包含"tag3",则在其名称.中添加"tag3“。

- -必须在文件/文件夹名称的末尾添加"tag3“,如果文件必须在文件扩展名之前添加。

- -为了示例起见,所有文件扩展名都是".txt“,但在实际情况下,它们可以是任何东西,因此需要考虑这一点。

-脚本必须忽略隐藏文件和文件夹(。然后..。)、dotfiles (.zshrc等)、

您可以在我的git中快速查看这个文件的历史,看看我尝试了什么:

v0.1.sh

脚本

总结一下我迄今所做的尝试:

尝试1-一次做所有的事情:

代码语言:javascript
复制
#!/bin/bash

set -e

declare -a STRINGS_TO_REPLACE
STRINGS_TO_REPLACE=("tag1" "tag2")
STRING_TO_ADD_IF_NOT_PRESENT="tag3"

rename_files_and_folders() {
    while IFS= read -r -d '' n; do
        for current_string in "${STRINGS_TO_REPLACE[@]}" ;
        do
            if [[ "$n" == *"$current_string"* ]] || ! [[ "$n" =~ .*"$STRING_TO_ADD_IF_NOT_PRESENT".* ]]; 
            then
                rename -d "$current_string" "$n"
                break;
            fi
        done
        # echo "$n"
    done < <(find . \( -depth -type d -path '*/\.*' -prune -o -not -name '.*' \) -print0)
}

rename_files_and_folders

我得到的输出让我相信它首先重命名了一个dir,然后尝试使用dir的旧名称重命名其中的文件,所以我尝试将文件的重命名和dir分割成不同的函数。我还认为,首先从所有文件和文件夹中删除"tag1“和"tag2”可能更容易一些,然后再到处添加"tag3“。

尝试2-尝试分别处理文件和文件夹(目录):

代码语言:javascript
复制
#!/bin/bash

set -e

declare -a STRINGS_TO_REPLACE
STRINGS_TO_REPLACE=("tag1" "tag2")
STRING_TO_ADD_IF_NOT_PRESENT="tag3"

rename_files_and_folders() {
    while IFS= read -r -d '' n; do

        # filename="${n##*/}"
        # currentfile="${n#.}"

        # if [[ -f "$n" ]] && [[ ! -d "$n" ]];
        # then

            for current_string in "${STRINGS_TO_REPLACE[@]}" ;
            do
                if [[ "$n" == *"$current_string"* ]]; 
                then
                    echo "Will rename $n"
                    test -e "$n" &&
                        rename -d "$current_string" "$n"
                    break;
                fi
            done

        # fi


    done < <(find . \( -type f -name "[!.]*" \) -print0)
}

rename_files_and_folders

rename_folders_and_dirs() {
    while IFS= read -r -d '' n; do


        if [[ -d "$n" ]];
        then

        for current_string in "${STRINGS_TO_REPLACE[@]}" ;
        do
            if [[ "$n" == *"$current_string"* ]]; 
            then
                echo "Will rename $n"
                test -e "$n" &&
                    rename -d "$current_string" "$n"
                break;
            fi
        done

        fi

    done < <(find . \( -depth -name "[!.]*" \) -print0)
}

rename_folders_and_dirs

当运行"Try 2“版本时,我得到以下输出:

代码语言:javascript
复制
Will rename ./test-data-files-and-folders-1/nested-test-folder-1/nested test file 2 tag1.txt
Will rename ./test-data-files-and-folders-1/nested-test-folder-1/nested test file 4 tag2.txt
Will rename ./test-data-files-and-folders-1/test file 14 tag1.txt
Will rename ./test-data-files-and-folders-1/nested-test-folder-2-tag1/nested test file 8 tag2.txt
Can't rename './test-data-files-and-folders-1/nested-test-folder-2-tag1/nested test file 8 tag2.txt' to './test-data-files-and-folders-1/nested-test-folder-2-/nested test file 8 tag2.txt': No such file or directory
Will rename ./test-data-files-and-folders-1/nested-test-folder-2-tag1/nested test file 5.txt
Can't rename './test-data-files-and-folders-1/nested-test-folder-2-tag1/nested test file 5.txt' to './test-data-files-and-folders-1/nested-test-folder-2-/nested test file 5.txt': No such file or directory
Will rename ./test-data-files-and-folders-1/nested-test-folder-2-tag1/nested test file 6 tag1.txt
Can't rename './test-data-files-and-folders-1/nested-test-folder-2-tag1/nested test file 6 tag1.txt' to './test-data-files-and-folders-1/nested-test-folder-2-/nested test file 6 tag1.txt': No such file or directory
Will rename ./test-data-files-and-folders-1/nested-test-folder-2-tag1/nested test file 7 tag3.txt
Can't rename './test-data-files-and-folders-1/nested-test-folder-2-tag1/nested test file 7 tag3.txt' to './test-data-files-and-folders-1/nested-test-folder-2-/nested test file 7 tag3.txt': No such file or directory
Will rename ./test-data-files-and-folders-1/test file 16 tag2.txt
Will rename ./test-data-files-and-folders-1/nested-test-folder-3 tag3/nested test file 12 tag2.txt
Will rename ./test-data-files-and-folders-1/nested-test-folder-3 tag3/nested test file 10 tag1.txt

在我看来,它似乎是首先重命名一个dir,然后尝试用一个旧的引用重命名文件,而我似乎无法绕过它。另外,find函数中的过滤器--一个仅用于文件,另一个用于文件夹--由于某种原因似乎无法工作。

其他我试过的比特和鲍勃:

代码语言:javascript
复制
## getting just the name of the file
filename="${n##*/}"

## removing the preceding dot
currentfile="${n#.}"

## filtering for just files and not dirs and vice versa
if [[ -f "$n" ]] && [[ ! -d "$n" ]];
then
    # ...
fi

任何帮助和建议都是非常感谢的!

谢谢!

编辑1

到目前为止,我提出了一个需要优化和清理的工作解决方案,它是最基本的,我可以使用优化技巧:

解决方案1- GitHub - WIP

代码语言:javascript
复制
#!/bin/bash

set -e

################################
## WORKING
##
## TODO: optimise
##
## WIP: [optimisation 1:]
## Instead of each function looping and going through all files and folders
## have one function to do the loop and pass the files and folders as arguments
## to all the other functions.
## Continue developing function `rename_files_and_folders_dirs_1`.
##
## [optimisation 2:]
## Expand features to take user input.
## For example call the script with flags/arguments/parameters/options
## which invoke different functions passing different arguments 
## such as tags to remove or tags to add.
## Note: This could likely make [optimisation 1:] redundant, so need to choose
## witch path to follow.
##
## References
## https://www.gnu.org/software/bash/manual/bash.html#Shell-Parameter-Expansion
## https://stackoverflow.com/questions/15012631/rename-files-and-directories-recursively-under-ubuntu-bash
## https://superuser.com/questions/213134/recursively-rename-files-change-extension-in-linux
## https://stackoverflow.com/questions/6509650/extract-directory-from-path
## https://stackoverflow.com/questions/6121091/get-file-directory-path-from-file-path/6121114
## https://stackoverflow.com/questions/13210880/replace-one-substring-for-another-string-in-shell-script
## https://tldp.org/LDP/abs/html/string-manipulation.html
## https://stackoverflow.com/questions/16623835/remove-a-fixed-prefix-suffix-from-a-string-in-bash
## https://unix.stackexchange.com/questions/311758/remove-specific-word-in-variable
## https://unix.stackexchange.com/questions/56810/adding-text-to-filename-before-extension
## https://stackoverflow.com/questions/45799657/bash-adding-a-string-to-file-name
## https://linuxize.com/post/bash-functions/
## https://bash.cyberciti.biz/guide/Pass_arguments_into_a_function
## https://stackoverflow.com/questions/6212219/passing-parameters-to-a-bash-function
## https://linuxacademy.com/blog/linux/conditions-in-bash-scripting-if-statements/
################################

declare -a STRINGS_TO_REPLACE
STRINGS_TO_REPLACE=("tag1" "tag2")

STRING_TO_ADD_IF_NOT_PRESENT="tag3"

################################

rename_files_remove_old_tags_arguments() {
    filepathnodot="${1#.}"
    # echo "$filepathnodot"

    justfilenamenopath="${1##*/}"
    # echo "$justfilenamenopath"

    justpathnofile=${1%/*}
    # echo "$justpathnofile"

    for current_string in "${STRINGS_TO_REPLACE[@]}" ;
    do
        if [[ "$justfilenamenopath" == *"$current_string"* ]]; 
        then
            # echo "Will rename $justfilenamenopath"
            test -e "$1" &&
                newfilename=$(echo "$justfilenamenopath" | sed "s/$current_string//g")
                mv -v "$1" "$justpathnofile/$newfilename"
            break;
        fi
    done
}

rename_files_remove_old_tags_arguments

################################

rename_files_remove_old_tags() {
    while IFS= read -r -d '' n; do

        filepathnodot="${n#.}"
        # echo "$filepathnodot"

        justfilenamenopath="${n##*/}"
        # echo "$justfilenamenopath"

        justpathnofile=${n%/*}
        # echo "$justpathnofile"

        for current_string in "${STRINGS_TO_REPLACE[@]}" ;
        do
            if [[ "$justfilenamenopath" == *"$current_string"* ]]; 
            then
                # echo "Will rename $justfilenamenopath"
                test -e "$n" &&
                    newfilename=$(echo "$justfilenamenopath" | sed "s/$current_string//g")
                    mv -v "$n" "$justpathnofile/$newfilename"
                break;
            fi
        done
    done < <(find . \( -type f -name "[!.]*" \) -print0)
}

rename_files_remove_old_tags

################################

rename_folders_dirs_remove_old_tags() {
    while IFS= read -r -d '' n; do
        for current_string in "${STRINGS_TO_REPLACE[@]}" ;
        do
            if [[ "$n" == *"$current_string"* ]]; 
            then
                # echo "Will rename $n"
                test -e "$n" &&
                    newfilename=$(echo "$n" | sed "s/$current_string//g")
                    mv -v "$n" "$newfilename"
                break;
            fi
        done
    done < <(find . \( -type d -name "[!.]*" \) -print0)
}

rename_folders_dirs_remove_old_tags

################################

rename_files_add_new_tags() {
    while IFS= read -r -d '' n; do
        
        filepathnodot="${n#.}"
        # echo "$filepathnodot"

        justfilenamenopath="${n##*/}"
        # echo "$justfilenamenopath"

        justpathnofile=${n%/*}
        # echo "$justpathnofile"

        if [[ ! "$justfilenamenopath" == *"$STRING_TO_ADD_IF_NOT_PRESENT"* ]]; 
        then
            # echo "Will rename $justfilenamenopath"
            test -e "$n" &&
                newfilename="${justfilenamenopath%.*} $STRING_TO_ADD_IF_NOT_PRESENT.${justfilenamenopath##*.}"
                mv -v "$n" "$justpathnofile/$newfilename"
        fi
    done < <(find . \( -type f -name "[!.]*" \) -print0)
}

rename_files_add_new_tags

################################

rename_folders_dirs_add_new_tags() {
    while IFS= read -r -d '' n; do
        
        filepathnodot="${n#.}"
        # echo "$filepathnodot"

        justpathnofile=${n%/*}
        # echo "$justpathnofile"

        if [[ ! "$n" == *"$STRING_TO_ADD_IF_NOT_PRESENT"* ]]; 
        then
            test -e "$n" &&
                newfilename="$n $STRING_TO_ADD_IF_NOT_PRESENT"
                mv -v "$n" "$newfilename"
        fi
    done < <(find . \( -type d -name "[!.]*" \) -print0)
}

rename_folders_dirs_add_new_tags

################################
################################
################################

rename_files_and_folders_dirs_1 () {
    while IFS= read -r -d '' n; do
        if [[ -f $n ]];
        then
            # echo "FILE <<< $n"
            rename_files_remove_old_tags_arguments "$n"
            # rename_files_add_new_tags "$n"
        elif [[ -d "$n" ]];
        then
            echo "DIR >>> $n"
            # rename_folders_dirs_remove_old_tags "$n"
            # rename_folders_dirs_add_new_tags "$n"
        fi
    done < <(find . \( -name "[!.]*" \) -print0)
}

# rename_files_and_folders_dirs_1

################################
################################
################################
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-10-20 11:59:02

到目前为止,我提出了一个需要优化和清理的工作解决方案,它是最基本的,我可以使用优化技巧:

解决方案1- GitHub - WIP

代码语言:javascript
复制
#!/bin/bash

set -e

################################
## WORKING
##
## TODO: optimise
##
## WIP: [optimisation 1:]
## Instead of each function looping and going through all files and folders
## have one function to do the loop and pass the files and folders as arguments
## to all the other functions.
## Continue developing function `rename_files_and_folders_dirs_1`.
##
## [optimisation 2:]
## Expand features to take user input.
## For example call the script with flags/arguments/parameters/options
## which invoke different functions passing different arguments 
## such as tags to remove or tags to add.
## Note: This could likely make [optimisation 1:] redundant, so need to choose
## witch path to follow.
##
## References
## https://www.gnu.org/software/bash/manual/bash.html#Shell-Parameter-Expansion
## https://stackoverflow.com/questions/15012631/rename-files-and-directories-recursively-under-ubuntu-bash
## https://superuser.com/questions/213134/recursively-rename-files-change-extension-in-linux
## https://stackoverflow.com/questions/6509650/extract-directory-from-path
## https://stackoverflow.com/questions/6121091/get-file-directory-path-from-file-path/6121114
## https://stackoverflow.com/questions/13210880/replace-one-substring-for-another-string-in-shell-script
## https://tldp.org/LDP/abs/html/string-manipulation.html
## https://stackoverflow.com/questions/16623835/remove-a-fixed-prefix-suffix-from-a-string-in-bash
## https://unix.stackexchange.com/questions/311758/remove-specific-word-in-variable
## https://unix.stackexchange.com/questions/56810/adding-text-to-filename-before-extension
## https://stackoverflow.com/questions/45799657/bash-adding-a-string-to-file-name
## https://linuxize.com/post/bash-functions/
## https://bash.cyberciti.biz/guide/Pass_arguments_into_a_function
## https://stackoverflow.com/questions/6212219/passing-parameters-to-a-bash-function
## https://linuxacademy.com/blog/linux/conditions-in-bash-scripting-if-statements/
################################

declare -a STRINGS_TO_REPLACE
STRINGS_TO_REPLACE=("tag1" "tag2")

STRING_TO_ADD_IF_NOT_PRESENT="tag3"

################################

rename_files_remove_old_tags_arguments() {
    filepathnodot="${1#.}"
    # echo "$filepathnodot"

    justfilenamenopath="${1##*/}"
    # echo "$justfilenamenopath"

    justpathnofile=${1%/*}
    # echo "$justpathnofile"

    for current_string in "${STRINGS_TO_REPLACE[@]}" ;
    do
        if [[ "$justfilenamenopath" == *"$current_string"* ]]; 
        then
            # echo "Will rename $justfilenamenopath"
            test -e "$1" &&
                newfilename=$(echo "$justfilenamenopath" | sed "s/$current_string//g")
                mv -v "$1" "$justpathnofile/$newfilename"
            break;
        fi
    done
}

rename_files_remove_old_tags_arguments

################################

rename_files_remove_old_tags() {
    while IFS= read -r -d '' n; do

        filepathnodot="${n#.}"
        # echo "$filepathnodot"

        justfilenamenopath="${n##*/}"
        # echo "$justfilenamenopath"

        justpathnofile=${n%/*}
        # echo "$justpathnofile"

        for current_string in "${STRINGS_TO_REPLACE[@]}" ;
        do
            if [[ "$justfilenamenopath" == *"$current_string"* ]]; 
            then
                # echo "Will rename $justfilenamenopath"
                test -e "$n" &&
                    newfilename=$(echo "$justfilenamenopath" | sed "s/$current_string//g")
                    mv -v "$n" "$justpathnofile/$newfilename"
                break;
            fi
        done
    done < <(find . \( -type f -name "[!.]*" \) -print0)
}

rename_files_remove_old_tags

################################

rename_folders_dirs_remove_old_tags() {
    while IFS= read -r -d '' n; do
        for current_string in "${STRINGS_TO_REPLACE[@]}" ;
        do
            if [[ "$n" == *"$current_string"* ]]; 
            then
                # echo "Will rename $n"
                test -e "$n" &&
                    newfilename=$(echo "$n" | sed "s/$current_string//g")
                    mv -v "$n" "$newfilename"
                break;
            fi
        done
    done < <(find . \( -type d -name "[!.]*" \) -print0)
}

rename_folders_dirs_remove_old_tags

################################

rename_files_add_new_tags() {
    while IFS= read -r -d '' n; do
        
        filepathnodot="${n#.}"
        # echo "$filepathnodot"

        justfilenamenopath="${n##*/}"
        # echo "$justfilenamenopath"

        justpathnofile=${n%/*}
        # echo "$justpathnofile"

        if [[ ! "$justfilenamenopath" == *"$STRING_TO_ADD_IF_NOT_PRESENT"* ]]; 
        then
            # echo "Will rename $justfilenamenopath"
            test -e "$n" &&
                newfilename="${justfilenamenopath%.*} $STRING_TO_ADD_IF_NOT_PRESENT.${justfilenamenopath##*.}"
                mv -v "$n" "$justpathnofile/$newfilename"
        fi
    done < <(find . \( -type f -name "[!.]*" \) -print0)
}

rename_files_add_new_tags

################################

rename_folders_dirs_add_new_tags() {
    while IFS= read -r -d '' n; do
        
        filepathnodot="${n#.}"
        # echo "$filepathnodot"

        justpathnofile=${n%/*}
        # echo "$justpathnofile"

        if [[ ! "$n" == *"$STRING_TO_ADD_IF_NOT_PRESENT"* ]]; 
        then
            test -e "$n" &&
                newfilename="$n $STRING_TO_ADD_IF_NOT_PRESENT"
                mv -v "$n" "$newfilename"
        fi
    done < <(find . \( -type d -name "[!.]*" \) -print0)
}

rename_folders_dirs_add_new_tags

################################
################################
################################

rename_files_and_folders_dirs_1 () {
    while IFS= read -r -d '' n; do
        if [[ -f $n ]];
        then
            # echo "FILE <<< $n"
            rename_files_remove_old_tags_arguments "$n"
            # rename_files_add_new_tags "$n"
        elif [[ -d "$n" ]];
        then
            echo "DIR >>> $n"
            # rename_folders_dirs_remove_old_tags "$n"
            # rename_folders_dirs_add_new_tags "$n"
        fi
    done < <(find . \( -name "[!.]*" \) -print0)
}

# rename_files_and_folders_dirs_1

################################
################################
################################
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/63296988

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档