book musings



missle defense



cultcha blog


scripts & programs

on the town



creds (PDF)



Simple String Replacement in Linux/Unix

Say you have a bunch of text files in a directory, and you need to change some text in all of them. This is where the replace command comes in handy.

The basic form of "replace" on the command line is this

#replace [TextToBeReplaced] [ReplacementString] -- [name of the file]
(Note for all these blog pages, you fill your own values in the brackets "[ ]").

The "--" tells the shell that the replacement string is finished and the next dab of letters is the file that the replacement operation is to be performed upon. Keep a space on either side of "--" .

You can replace multiple strings in one command, i.e.

#replace [OldString1] [NewString1] [OldString2] [OldString2] -- [name of the file]
You can change multiple files in one action, by simply naming all the files, each separated by a space, i.e. "file1.txt file2.txt")

You also can use a wild card (*) as part ("*.html"), or all ("*") of the designation for the files you want to be modified, but be careful to not inadvertently replacing strings you didn't intend to replace, especially in cases where the replaced strings are short.

You can also do simple search and replace with Perl, if you have Perl installed on your Linux system. At the command line, the basic format is:
perl -p -i -e 's/[Text2bReplaced]/[ReplacementText]/g' [Name of File]
There are some escape codes to deal with, for complicated strings. If you have more than one line you are replacing. For more than one line add "\n" at end of the every line. Put a "\" in front of every single (') and double (") quote.
Lastly, I'm not sure where else to put this, so I'll tuck it in here and let the search engines find it. If you want to convert DOS files to Unix ones on a Unix machine, the Perl command is this:
perl -i -pe 's/\r//g' [FilesYouWantConverted]