LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   Replace a specific word every three occurences (https://www.linuxquestions.org/questions/programming-9/replace-a-specific-word-every-three-occurences-917565/)

udiubu 12-07-2011 08:34 AM

Replace a specific word every three occurences
 
Dear all,

I got this problem today.

I have a log file with several lines and columns.
In a column I have for example this succession of strings:

Picture
word3
word3
word3
Picuture
word3
Picture
word3
word3
Picture
word3
word3
Picture
word3

What I need is a command that replace the string "word3" with let's say " bob" only every three occurences of the "word3" itself, as below:

Picture
BOB
word3
word3
Picuture
BOB
Picture
word3
word3
Picture
BOB
word3
Picture
word3

I'm using this command that of course changes all of them, recoursively:

awk '{for (i=1; i <= NF; i++) if ($i == "word3") $i = "BOB"; print $0}' file.log > file1.txt

Any suggestions would be highly appreciated!

All the best,

Udiubu

udiubu 12-07-2011 09:12 AM

First solution:

(1) sub every three..

awk '/word3/{c++;if(c==3){sub("word3","BOB");c=0}}1' file.log >file.txt

(2) sub every two..

awk '/word3/{c++;if(c==2){sub("word3","JACK");c=0}}1' file.txt >file1.txt

Cedrik 12-07-2011 09:24 AM

Quote:

Originally Posted by udiubu (Post 4544281)
First solution:

(1) sub every three..

awk '/word3/{c++;if(c==3){sub("word3","BOB");c=0}}1' file.log >file.txt

(2) sub every two..

awk '/word3/{c++;if(c==2){sub("word3","JACK");c=0}}1' file.txt >file1.txt

Nice, but why not do it in one pass, like:
Code:

awk '/word3/{if(!c++){sub("word3","BOB");}if(c==3)c=0;}1' file.log > file1.txt

udiubu 12-07-2011 09:41 AM

Hi Cedrik,

That works, too!!
Thanks..

I'm doing these three steps now as I found useful to have these three occurences named with three different names.

Have a nice day.

All the best,

Udiubu

Nominal Animal 12-07-2011 10:38 AM

Quote:

Originally Posted by Cedrik (Post 4544287)
Code:

awk '/word3/{if(!c++){sub("word3","BOB");}if(c==3)c=0;}1' file.log > file1.txt

You could make it even simpler:
Code:

awk '/word3/ { if (++c == 3) { c=0; sub(/word3/, "BOB") } } 1' file.log > file1.txt

Cedrik 12-07-2011 10:58 AM

Quote:

Originally Posted by Nominal Animal (Post 4544340)
You could make it even simpler:
Code:

awk '/word3/ { if (++c == 3) { c=0; sub(/word3/, "BOB") } } 1' file.log > file1.txt

Simpler indeed, nice ;)


All times are GMT -5. The time now is 08:31 PM.