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?
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 `…`
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With