top of page
Shell script to replace old-pattern with new-pattern in all text files
Automate text replacement across files with this shell script.
Linux shell script allows the user to find and replace the text from the file. Here we will use the sed command to find and replace the text. By using SED you can edit files even without opening them.
vi replace.sh
#!/bin/sh
# replace $1 with $2 in $*
# usage: replace "old-pattern" "new-pattern" file [file...]
OLD=$1 # first parameter of the script
NEW=$2 # second parameter
shift ; shift # discard the first 2 parameters: the next are the file names
for file in $* # for all files given as parameters
do
# replace every occurrence of OLD with NEW, save on a temporary file
sed "s/$OLD/$NEW/g" ${file} > ${file}.new
# rename the temporary file as the original file
/bin/mv ${file}.new ${file}
done
Here is the sample output of the above script
More ways to use find & replace shell script
Replace the nth occurrence of a pattern in a line - $sed 's/unix/linux/2' shell.txt
You can also use to Parenthesize first character of each word
$ echo "Welcome To DBA Genesis" | sed 's/\(\b[A-Z]\)/\(\1\)/g'
bottom of page