Created
May 13, 2018 09:32
-
-
Save awwsmm/e81f17fb169483a0042210251fc5ef71 to your computer and use it in GitHub Desktop.
Bash functions to find and replace across multiple files / rename multiple files
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
##---------------------------------------------------------------------------- | |
## | |
## functions to find and replace within multiple files or in file names | |
## | |
##---------------------------------------------------------------------------- | |
# if dir, return dir; if symlink, return dir that symlink points to | |
function unsym(){ | |
echo "$(python -c "import os; print(os.path.realpath('"$1"'))")" | |
} | |
# the below three functions all use the following scheme: | |
# $1: where to look, ex: dir/*.txt | |
# $2: what to look for, ex: oldstring | |
# $3: what to replace it with, ex: new_string | |
# example: | |
# $ findAndRename "foo/bar*.txt" _2017 _2018 | |
# ... will replace any occurrences of "_2017" in the names of | |
# all *.txt files (whose names begin with "bar") in the foo/ | |
# directory with "_2018" | |
# find and replace across multiple files | |
function findAndReplace(){ | |
mypath=$(unsym "$1") | |
echo "Replacing '$2' with '$3' for these files: $mypath" | |
echo "(Note: if you're using a glob in the path, put the first argument in quotes.)" | |
perl -pi -w -e "s/$2/$3/g;" $mypath | |
} | |
# find files and rename them | |
function findAndRename(){ | |
mypath=$(unsym "$1") | |
echo "Replacing '$2' with '$3' in the names of these files: $mypath" | |
echo "(Note: if you're using a glob in the path, put the first argument in quotes.)" | |
for f in $mypath; do mv -- "$f" "${f//$2/$3}"; done | |
} | |
# change name of Java class for all files in a given directory | |
function changeClassName(){ | |
findAndRename "$1" "$2" "$3" | |
findAndReplace "$1" "$2" "$3" | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment