Using Perl to replace a line only on a specific line in a file

I have a script that I am using to find and replace large scale. When a match is found in a specific file, I write down the filename and line number.

What I want to do for each filename, pair of line numbers, change the line from <foo>

to to <bar>

just that line of the file.

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

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

      

This, however, I believe it ignores $. = $lineNum

and just does s/$find/$replace/

for the whole file, which is very bad.

Any ideas how I can do this?

+3


source to share


1 answer


You are using assignment =

instead of comparison ==

.

Using:

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

      



where there are some caveats about the content $find

, $replace

and $lineNum

that probably won't be a problem. Reservations are problems such as $find

cannot contain a forward slash; $replace

cannot contain forward slashes; $lineNum

there must be a line number; beware of other extraneous extra characters that can confuse the code.

I don't understand why you want to capture the standard output of the Perl process when writing to a file and not to standard output. Thus, the assignment is run

implausible. And if necessary, you would probably be better off using run=$(perl …)

with notation $()

instead of `…`

.

+4


source







All Articles