Skip to content

Instantly share code, notes, and snippets.

@cisoun
Created October 17, 2019 07:40
Show Gist options
  • Save cisoun/075086bfa7b73051eeb321ee6379c662 to your computer and use it in GitHub Desktop.
Save cisoun/075086bfa7b73051eeb321ee6379c662 to your computer and use it in GitHub Desktop.
Rename folders, files and their content at once.
#/usr/bin/env bash
#
# rename.sh
#
# Replace any occurency of "<source>" to "<target>" in a given <directory>.
# This apply to (sub)folders/files name and files content.
# Think about it like a refactoring function.
#
# Usage: rename.sh <source> <target> <directory>
#
set -eu
if [[ $# -lt 3 ]]; then
echo "usage: $0 <source> <target> <directory>" 1>&2
exit 1
fi
source=$1
target=$2
path=$3
# Changes text in files.
files=$(grep -rl "$source" "$path")
for i in $files; do
sed -i '' "s/$source/$target/g" $i
done
# Change files name.
folders=$(find $path -name "*$source*" -type d)
for i in $folders; do
name="${i/$source/$target}"
mv $i $name
done
files=$(find $path -name "*$source*" -type f)
for i in $files; do
name="${i/$source/$target}"
mv $i $name
done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment