One of things I always seem to be doing is searching for strings in files and changing them. I’ve gotten used to using Sed and VI for this. But perl also makes it easy to do via the command line.
Consider the following text file:
$ cat resolv.conf
search theunixzone.com
nameserver 10.1.1.1
nameserver 10.1.1.2
nameserver 10.1.1.3
By doing a command similar to the following, you can easily change strings from the command line.
$ perl -pi -w -e ’s/10.1.1/10.5.5/g;’ resolv.conf
$ cat resolv.conf
search theunixzone.com
nameserver 10.5.5.1
nameserver 10.5.5.2
nameserver 10.5.5.3
Often, the benefit of using Perl to do this is the fact that you can specify multiple filesnames, or use a wildcard, and edit the files in-place — without writing to a temporary file. I use this often for making mass changes to DNS Zone files, etc.
Let’s look at the command line argruments we used. The “-pi” allows Perl to edit the file in place. The “-w” enables many useful warnings. And, finally, the “-e” basically says that the next string in quotes is the perl program instruction you want to exectute. In this case, we are changing all occurances of the string “10.1.1″ and changing it to “10.5.5″. This is a regular expression which we’ll cover more of in the future.
![[del.icio.us]](http://www.theunixzone.com/wp-content/plugins/bookmarkify/delicious.png)
![[Digg]](http://www.theunixzone.com/wp-content/plugins/bookmarkify/digg.png)
![[Facebook]](http://www.theunixzone.com/wp-content/plugins/bookmarkify/facebook.png)
![[Twitter]](http://www.theunixzone.com/wp-content/plugins/bookmarkify/twitter.png)