Renaming files with Bash, removing prefix and suffix

Another approach, for fun, using regular expressions:

regex='prefix - (.*) - suffix.txt'
for f in *.txt; do
    [[ $f =~ $regex ]] && mv "$f" "${BASH_REMATCH[1]}.txt"
done

Actually, using the simple pattern ‘*.txt’ here has two problems:

  1. It’s too broad; you may need to apply the regex to a lot of non-matching files.
  2. If there are a lot of files in the current directory, the command line could overflow.

Using find complicates the procedure, but is more correct:

find . -maxdepth 1 -regex 'prefix - .* - suffix.txt' -print0 | \
  while read -d '' -r; do
   [[ $REPLY =~ $regex ]] && mv "$REPLY" "${BASH_REMATCH[1]}.txt"
  done

Leave a Comment