Shell/Bash shortcut for bulk renaming of files in a folder

There is prename, that allows you to use REGEX:

prename 's/^.*-doc-(.*\.txt)$/doc-$1/'  *.txt

Use the option -n to simulate:

prename -n 's/^.*-doc-(.*\.txt)$/doc-$1/'  *.txt

Note: This is the shipped as rename in many Linux distributions, but not in all of them -- so I'm using the canonical name for the utility that comes with Perl.


I would suggest something like this:

for i in *-doc-*.txt; do mv "$i" "${i/*-doc-/doc-}"; done

${i/*-doc-/doc-} replaces the first occurrence of *-doc- with doc-.

If you need to do more than one replacement (see comment number 1), you need to use the ${var//Pattern/Replacement} variant. If you need to replace the beginning of the name you need to use ${var/#Pattern/Replacement}, if you need to replace the end (ie: the extension) you need to use the ${var/%Pattern/Replacement} form.

See Shell Parameter Expansion for more details. This expansion is bash specific.


If you have rename then, rename 's/^.*-doc-/doc-/' *.txt should do the trick.


If you want to recurse into sub-directories, there is also:

find . -maxdepth N -type f -name "$pattern" | sed -e 'p' -E -e "s/$str1/$str2/g" | xargs -n2 mv

On system that automatically support extended Regexps, you can leave away the -E.

Advantages:

  • recurses into sub-directories
  • you can control the maxdepth of the recursion
  • you can rename files and/or directories (-type f|d)

Disadvantages:

  • slightly more complicated regexps, because you have to strip out the path to get at the file name

(answer amended from here)