REPLACE A STRING IN A FILE FROM LINUX COMMAND LINE USING SED

if you want to replace a string in file without entering the file, then sed can be used to solve this purpose

To replace a single text in a file

[oracle@exdbadm01 ~]$ touch file
[oracle@exdbadm01 ~]$ echo "replace_me" > file
[oracle@exdbadm01 ~]$ cat file
replace_me
[oracle@exdbadm01 ~]$ sed -i 's/replace_me/new_me/' file
[oracle@exdbadm01 ~]$ cat file
new_me

To replace multiple string with the same text in a file,then follow below steps

[oracle@exdbadm01 ~]$ echo "replace_me_global" >> file
[oracle@exdbadm01 ~]$ cat file
new_me
replace_me_global
[oracle@exdbadm01 ~]$ sed -i 's/replace_me/new_me/g' file
[oracle@exdbadm01 ~]$ cat file
new_me
new_me_global

To replace a string as per line number, use the below combinations

[oracle@exdbadm01 ~]$ sed -i '2s/new_me/replace_me_again/' file
[oracle@exdbadm01 ~]$ cat file
new_me
replace_me_again_global

To take backup of the original file and replace the string

[oracle@exdbadm01 ~]$ sed -i.bak '1s/new_me/replace_me_again/' file
[oracle@exdbadm01 ~]$ cat file
replace_me_again
replace_me_again_global

[oracle@exdbadm01 ~]$ ls -lrt *file*
-rw-r--r-- 1 oracle oinstall 31 Sep 11 04:31 file.bak
-rw-r--r-- 1 oracle oinstall 41 Sep 11 04:32 file

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s