• Arun Kumar

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
# 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
# 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}

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'


Recent Posts

See All

Oracle 19c Installation on Linux

Oracle 19c adds more features to Oracle database and this article demonstrates Oracle 19c installation on Linux 7. We will be using Oracle Linux 7 and Oracle Database 19.3 softwares for this activity.

Basic Linux Commands

This article describes basic Linux commands that you must know as a system or database administrator. Below commands in Linux help you manage any Linux server fast and smoothly. Linux Command List Che

Linux Firewall with iptables and firewalld

In this article will be covering details regarding iptables and firewalld which helps in Linux firewall management. We will also be looking at how to enable specific ports (1521 for Oracle) inside ipt