[Bash] List All Files in Directory Recursively and Rename


Question:

I have a lot of files under content/articles directory. The filenames are something like abc-def-ghi#en.rst. I want to rename them all and replace the # with %. For example, abc-def-ghi#en.rst will be renamed as abc-def-ghi%en.rst, how do I do it?

Answer:

list-files-recursively-rename.sh | repository | view raw
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
#!/bin/bash
# list-files-recursively-rename.sh
# List All Files in Directory Recursively and Rename

count=0 # count the number of processed files

# list all files recursively
for file in $(find content/articles -type f)
do
  # rename the file by replacing # with %
  new=`echo $file | sed 's/#/%/g'`
  if [ $file != $new ]; then
    count=$((count+=1))
    echo "$count . $file => $new"
    # files are version controlled by Git, so use git mv
    git mv $file $new
  fi
done

References:

[1]List all files in a directory recursively but exclude directories themselves
[2]Using sed to mass rename files
[3]How to increment a variable in bash?