LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   SED replace string by occurrence (https://www.linuxquestions.org/questions/programming-9/sed-replace-string-by-occurrence-625794/)

uttam_h 03-05-2008 12:48 AM

SED replace string by occurrence
 
hi all,
I have a text file with following content

PAGENUMBER
asasasa
asasasa
PAGENUMBER
sasasasasa
PAGENUMBER

using sed i want to replace PAGENUMBER by occurrence count

eg

1
asasasa
asasasa
2
sasasasasa
3


Thanks and Regards,
uttam hoode

angrybanana 03-05-2008 01:06 AM

Not sed, but awk... works with your sample data.
Code:

awk '/PAGENUMBER/{$0=++i}1' file
If you need the code explained, or need me to write an easier to understand one just ask.

uttam_h 03-05-2008 02:23 AM

this is working fine.
how can i replace the string present in the file by output of awk without using redirection (>). In sed its called inline edit. Is it possible with awk?

radoulov 03-05-2008 06:09 AM

Quote:

Originally Posted by uttam_h (Post 3078594)
this is working fine.
how can i replace the string present in the file by output of awk without using redirection (>). In sed its called inline edit. Is it possible with awk?

No,
why you don't want to use redirection?

Anyway:

Code:

{ rm file&&awk >file '$0=/^PAGENUMBER/?++c:$0';}<file

osor 03-05-2008 07:59 PM

Quote:

Originally Posted by uttam_h (Post 3078594)
Is it possible with awk?

No, but it is in Perl as the -i flag. E.g.,
Code:

perl -pi -e 's/PAGENUMBER/++$a/e' file

uttam_h 03-05-2008 10:02 PM

Thanks angrybanana,radoulov and osor for the reply.

I will use the solution given by osor.

perl -pi -e 's/PAGENUMBER/++$a/e' file

Thanks and Regards,
uttam hoode


All times are GMT -5. The time now is 03:41 PM.