How to search and replace text where line contains some specific string in Linux shell ?

Today we will look how to search some text in a file and replace specific string on the searched line.

For this, we will use sed command i.e. Linux Stream editor command to achieve this quickly.

First create a file like below.

[root@nglinux ]# cat file2 
Welcome to NGELinux.com
This tutorial shows us how to
replace a text
[root@nglinux ]#

 

1. Replace all(g-global) occurrence of “shows” with “explains”.

[root@nglinux ]# cat file2 | sed '/tutorial/s/shows/explains/g'
Welcome to NGELinux.com
This tutorial explains us how to
replace a text
[root@nglinux ]# 

 

2. Start the search from 2nd line to last line.

[root@nglinux ]# cat file2 | sed -n '2,$p' |sed '/tutorial/s/shows/explains/g'
This tutorial explains us how to
replace a text
[root@nglinux ]# 

Similar to above examples, we can search and replace any text in the file as per the matched pattern.

Leave a Reply

avatar
  Subscribe  
Notify of