[ACCEPTED]-Renaming files with Bash, removing prefix and suffix-file-rename

Accepted answer
Score: 10

Another approach, for fun, using regular 3 expressions:

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

Actually, using the simple pattern 2 '*.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 1 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
Score: 3

If you have access to GNU sed, you could use some 1 regex to perform something like:

for i in *.txt; do mv "$i" "$(echo $i | sed -r 's/([^-]*)\s-\s(.*)\s-\s([^-]*)\.txt/\2.txt/')"; done
Score: 0

you could use this:

find . -name "*.txt" -print0 | awk -v RS="\0" -v ORS="\0" '{print $0;sub(/^prefix - /,""); sub(/ - suffix.txt$/,".txt"); print $0; }' | xargs -0 -n 2 mv

which could be written 1 more clearly as:

find . -name "*.txt" -print0 |
awk -v RS="\0" -v ORS="\0" '{
  print $0;
  sub(/^prefix - /,""); 
  sub(/ - suffix.txt$/,".txt"); 
  print $0;
}' |
xargs -0 -n 2 mv
Score: 0

If you have emacs installed. You can use the 1 dired feature.

In bash:

# open your dir with emacs
emacs /path/to/your/dir

In emacs:

  • Press *%Enter\.txt$Enter to mark all txt files.
  • Press %rEnter.*- \(.*\) -.*Enter\1.txtEnter to rename.

More Related questions