Developer

Tech Tip: Modify Linux files with Perl

Here's how to modify Linux files with Perl.

When you're writing scripts or installation programs that need to modify data in specific files, the ability to automatically change files can be a very useful thing. For example, this ability comes in handy when you have a file from which you need to remove a certain string or word, when you're changing an IP address in a number of files, and so on.

Manually modifying these files can be time-consuming, especially if it's a repetitive task. However, you can use the Perl program to accomplish this. All Linux distributions come with this program. Execute the following:

$ perl -pi -e 's|[old_string]|[new_string]|g' [file]

The strings can be simple words or regular expressions. Let's say you changed the location of a directory (e.g., from /var/spool/mail to /var/spool/messages), and you want to change every file in the /etc directory to reflect the path change. Execute the following:

$ find /etc -type f| xargs perl -pi -e 's|\/var\/spool\/mail|\/var\/spool\/messages|g'

In this example, we use find and xargs to ensure that the system only runs the command against regular files—not accidentally against directories or other file types. This also walks the /etc directory tree and will recursively change all files.

We've written the paths as \/var rather than /var because we need to escape the / character, which we can also use as a delimiter in the Perl expression. (Instead of using |, you can also use /, #, and @ as delimiters.)

To remove a word from an entire file, execute the following:

$ perl -pi -e 's|myword||g' file

This basically replaces "myword" with nothing. (Note that there's no space between the second and third delimiters.)

Using Perl in this fashion, you can get extremely creative when modifying configuration files or any other type of data. Think of it as an automatic search-and-replace function.

Editor's Picks

Free Newsletters, In your Inbox