Search code examples
bashshellcommand-linerenamebatch-rename

bash - mass renaming files with many special characters


I have a lot of files (in single directory) like:

[a]File-. abc'.d -001[xxx].txt

so there are many spaces, apostrophes, brackets, and full stops. The only differences between them are numbers in place of 001, and letters in place of xxx. How to remove the middle part, so all that remains would be

[a]File-001[xxx].txt

I'd like an explanation how such code would work, so I could adapt it for other uses, and hopefully help answer others similar questions.


Solution

  • Here is a simple script in pure bash:

    for f in *; do            # for all entries in the current directory
      if [ -f "$f" ]; then    # if the entry is a regular file (i.e. not a directory)
        mv "$f" "${f/-*-/-}"  # rename it by removing everything between two dashes 
                              # and the dashes, and replace the removed part 
                              # with a single dash
      fi
    done
    

    The magic done in the "${f/-*-/-}" expression is described in the bash manual (the command is info bash) in the chapter 3.5.3 Shell Parameter Expansion

    The * pattern in the first line of the script can be replaced with anything than can help to narrow the list of the filles you want to rename, e.g. *.txt, *File*.txt, etc.