Ik I can use grep to find filenames with specific characters and then print that to a list but idk how to utilize said list to rename. I found another solution which’s using mv but couldn’t figure out how to make it work w subdirectories. I think using both grep and mv in unison’s the answer just idk how to do it. plz halp

  • thingsiplay@lemmy.ml
    link
    fedilink
    arrow-up
    1
    ·
    23 hours ago

    Here is a different approach involving loops instead. This allows for greater control over what happens. Note in this script the rename() function just echos the command without any effect. This is just a demonstration, so you can experiment with the arguments and edit the script first.

    If you have only one argument that is then used to search with find, no slashes in search term is allowed. I didn’t want complicate the script further and left it as it is.

    #!/usr/bin/env bash
    
    # Rename files
    #
    # This script has 3 ways to input filenames.
    #
    # If only one argument is given, then its used as search term to match
    # filenames. If more than one argument
    #
    # is given, then instead searching for files it will rename all given
    # filenames.
    #
    # If no filename is given, then list of files will be read from stdin pipe. In
    # that case combine it with a tool like find.
    #
    # Change the below function rename() to set what to do with each old filename.
    # The default is to echo, so change that first.
    #
    #
    # Examples:
    #
    #   renameclean.sh '*txt'
    #
    #   renameclean.sh 'dir1/random?file.txt' 'dir2/subdir/anotherfile.zip'
    #
    #   find dir -type f -name '*.txt' | renameclean.sh
    
    rename() {
        old="${1}"
        new="${old}"
    
        # Special characters such as ?, * or " need a backslash to match them
        # literally.
        new="${new/\?/REPLACEMENT}"
        new="${new/\*/REPLACEMENT}"
        new="${new/\"/REPLACEMENT}"
    
        echo mv -- "${old}" "${new}"
    }
    
    # If no argument is given, then read list from stdin.
    if [ "${#}" == 0 ]; then
        while read -r file; do
            rename "${file}"
        done
    # If one argument is given, then use it as a search name.
    elif [ "${#}" == 1 ]; then
        find . -type f -name "${1}" -print0 |
            while read -r -d $'\0' file; do
                rename "${file}"
            done
    # If more than one argument is given, then use all arguments as filenames to
    # rename.
    else
        for file in "${@}"; do
            rename "${file}"
        done
    fi