Replace A Single Line Of Text In Multiple Files On Mac OSX

Earlier I was transferring some configuration files from an application on a Windows 7 computer to an application on a OSX Lion computer. The location of a file referenced in the configuration files had changed so I needed to update about a hundred different INI files with the new location. Doing this on OSX is very easy using perl as long as you get the syntax correct as it can be tricky if there are multiple quotes and or slashes. Below is a quick example of a perl command used to replace a single line of text in multiple files without having to modify each file individually.

Modify Single Line Of Text In Multiple Files On OSX:

First open a terminal window and change into the directory that contains the files you want to modify. Once you are in the directory note the line of text you want to replace and the line of text you will be using to replace the original text. Below is an example of what your perl command may look like followed by a brief explanation of each part of the command.

Perl Command Used To Replace Text In Multiple Files:

perl -pi~ -e 's/S:"Some Variable"=C:\folder1\folder2\folder3\folder4\config.txt/S:"Some Variable"=/Users/alex/Documents/folder/subfolder/config.txt/' *.ini

Perl Command Details:

  • perl   –> the actual perl command
  • -pi~  –> -p :: assume loop like -n but print line also, like sed, -i[extension] :: edit <> files in place (makes backup if extension supplied) – notice in our case that ~ was supplied as an extension so files will be backed up like file.txt~ if the original filename was file.txt.
  • -e      –> one line of program (several -e’s allowed, omit programfile)
  • ‘s/OLDTEXT/NEWTEXT/’ –> this tells perl to search for OLDTEXT and when found replace it with NEWTEXT

Please also note that when “, \, or / are used within the OLDTEXT or NEWTEXT sections of the command that they need to be preceded by a back slash or \. This tells perl to not execute the symbol as a command so if you have a quote for instance it won’t close the string but instead will print the quote as text in the search string. Making sure you have the correct amount of back slashes in place is critical to getting this command to function properly.

List Price: $49.99 USD
New From: $24.39 USD In Stock
Used from: $17.39 USD In Stock

List Price: $39.99 USD
New From: $21.54 USD In Stock
Used from: $13.48 USD In Stock