1. Home
  2. Linux
  3. Using Sed,ex & perl commands to find and replace a text in Linux

Using Sed,ex & perl commands to find and replace a text in Linux

Question: I would like to replace a text with a link in anchor tag of a html file. The challenge is that, the project contains hundreds of such HTML files and replacing a text in all those files manually is not smart way of doing it. So the question is, how can I do the same using a single command in Linux?


Using sed command in Linux:

sed -i 's/#\(.*logo\)/domain.ca\1/' $file

The above command searches for the line that contains the pattern logo and replaces “#” with a link (for e.g., a domain.ca)

Linux - pattern match

You can also pass multiple files for the above command as shown below.

An another variation of the above command is:

sed -i '/logo.png/ s/#/domain.ca/' *.html

Using perl command:

perl -i -pe 's/#/domain.ca/ if /logo.png/' about-us.html

The command is very straight forward – search the text and replace it with certain string if and only if it finds a matching string on that line of the file.

All the above commands does the same job, but it only differs in how you put in your regular expression.

Use Vim in ex mode (can’t be used with multiple files):

ex -sc '/logo/s/#/http:\/\/domain.ca\//|x' about-us.html

In the above command the regular expression ‘/logo/s/#/http:\/\/domain.ca\//|x‘ consists of ‘s’ and ‘x’ – where ‘s’ is for substitute and ‘x’ is for save and close the file.

Note: The above command uses vim, you can’t pass multiple files. You need to execute this command manually for each and every file to be replaced.

Updated on September 2, 2017

Was this article helpful?

Related Articles

Add A Comment