5

[Bash] List All Files in Directory Recursively and Rename

 3 years ago
source link: http://siongui.github.io/2015/02/02/bash-list-files-recursively-and-rename/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

[Bash] List All Files in Directory Recursively and Rename

February 02, 2015

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

#!/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?


Recommend

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK