bneigher
bneigher

Reputation: 848

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

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?

Upvotes: 5

Views: 3189

Answers (1)

Jonathan Leffler
Jonathan Leffler

Reputation: 753615

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 `…`.

Upvotes: 7

Related Questions