LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - General (http://www.linuxquestions.org/questions/linux-general-1/)
-   -   Perl command to replace string by line numbe (http://www.linuxquestions.org/questions/linux-general-1/perl-command-to-replace-string-by-line-numbe-819098/)

andiramesh_m 07-10-2010 11:05 AM

Perl command to replace string by line numbe
 
Hi,
I want to know the Perl command to replace a string by pointing the line number. I know how to replace a string without pointing a line number but I am in need to replace only the two matching string in a file. Any help is appreciated.

Thanks

David the H. 07-11-2010 04:49 AM

I'm not sure what "pointing to" means here, but if I'm reading correctly, you want to replace a text string with the current line number?

I don't know about perl, but it's simple to do in (gnu) awk.
Code:

awk 'gsub(/string/,NR)1' filename

syg00 07-11-2010 05:02 AM

Maybe it's just me, but that as a first post, seems like homework.

andiramesh_m 07-13-2010 11:06 PM

David,
Thanks for your help.

I am looking for a equivalent perl command like the below sed command.

eg:
sed '100s/error/debug/g' <file name>

(This will replace the word "error" to "debug" at line number 100).

Similarly what is the perl command to replace a string available at x line number?

Sed command would not modify the existing file rather we should redirect it to a new file but perl would directly modify the existing file

andiramesh_m 07-13-2010 11:08 PM

David,
Thanks for your help.

I am looking for a equivalent perl command like the below sed command.

eg:
sed '100s/error/debug/g' <file name>

(This will replace the word "error" to "debug" at line number 100).

Similarly what is the perl command to replace a string available at x line number?

Sed command would not modify the existing file rather we should redirect it to a new file but perl would directly modify the existing file

vigilandy 07-14-2010 04:12 AM

perhaps you need to look at the -i option for sed.

David the H. 07-15-2010 12:00 PM

I know hardly anything about perl syntax, but after a quick google search and a couple of minutes on this site, I got this to work:
Code:

perl -i -ple 's/error/debug/g if $. == 100; close ARGV if eof' file
Apparently the last part is only necessary if you're processing multiple files, as you need to reset the $. count for each new file.

There are also examples there on using ranges and how to exclude lines. Check it out. :)


All times are GMT -5. The time now is 11:22 PM.