top of page
DBAGenesis_png.png

Shell script to replace old-pattern with new-pattern in all text files

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

shell script to replace old-pattern with new-pattern in all text files


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'

Become a top notch dba with DBA Genesis
Become a DBA with DBA Genesis.png
bottom of page