Replacing Commands for Linux Files - Using Perl and Sed
A file may contain different types of strings, numbers, special characters, etc..,. We can directly edit the file using a file editor, but that applies to a single file only. If we wish to search and replace a particular word or number on multiple files, it is a burden to edit manually on every single file. In such situations we use Perl and Sed commands to achieve it.
In this article we are going to see how to replace strings, numbers in a file or a set of files using perl command and sed command.
Using Perl:
Perl is the command interpreter of the Perl programming language. Perl has a large number of options that can be useful on the command line. In this article we will be seeing how to perform search and replace alone as stated earlier.
Syntax:
perl -pi -e 's/search/replace/g' File1 File2 File3
The above syntax is the basic one, but it differs according to the type of search and replacement (Strings, Numbers, Special Characters).
Demo file:
Our demo file will be,
Replacing a string on files:
To replace a string on the files, we can use the basic syntax.
Replacing Numbers on files:
The basic syntax applies to the normal numbers but if the number is in float or an IP we need to add an escape character ( \ ) before the period.
On the above command the perl search for 27.5 on the file and replace it with 34.7. Such scenarios happens when we want to change an IP address on files.
Replacing strings with specials characters on files:
We use the same escape character ( \ ) before the special characters. This applies to words consist of -,<,>,(,) or any other symbols.
Comments