Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Perl to replace a string in only a certain line of file

Tags:

bash

perl

edit

I have a script that I am using for a large scale find and replace. When a match is found in a particular file, I record the file name, and the line number.

What I want to do is for each file name, line number pair, change a string from <foo> to <bar> on only that line of the file.

In my shell script, I am executing a find and replace command on the file given the line number...

run=`perl -pi -e "s/$find/$replace/ if $. = $lineNum" $file`

This however I believe has been ignoring the $. = $lineNum and just does the s/$find/$replace/ on the whole file, which is really bad.

Any ideas how I can do this?

like image 936
bneigher Avatar asked Jul 02 '15 03:07

bneigher


1 Answers

You are using assignment = instead of comparison ==.

Use:

perl -pi -e "s/$find/$replace/ if $. == $lineNum" $file

where there are some caveats about the content of $find, $replace and $lineNum that probably aren't going to be a problem. The caveats are issues such as $find cannot contain a slash; $replace can't contain a slash either; $lineNum needs to be a line number; beware other extraneous extra characters that could confuse the code.

I don't see why you'd want to capture the standard output of the Perl process when it writes to the file, not to standard output. So, the assignment to run is implausible. And if it is necessary, you would probably be better off using run=$(perl …) with the $() notation in place of `…`.

like image 200
Jonathan Leffler Avatar answered Oct 01 '22 10:10

Jonathan Leffler