Reputation: 2493
I have a file like this
Go to Vegas
Play the blackjack
Earn a lucky wad
Find a hot chick
Do the best part now
Go to Vegas
Play the blackjack
Earn a lucky wad
Find a hot chick
Do the best part now
Go to Vegas
Play the blackjack
Earn a lucky wad
Find a hot chick
Do the best part now
Go to Vegas
Play the blackjack
Earn a lucky wad
Find a hot chick
Do the best part now
Go to Vegas
Play the blackjack
Earn a lucky wad
Find a hot chick
Do the best part now
I want to add a line wait after every 3rdh match of "Find a hot chick"
So the above should read.
Go to Vegas
Play the blackjack
Earn a lucky wad
Find a hot chick
Do the best part now
Go to Vegas
Play the blackjack
Earn a lucky wad
Find a hot chick
Do the best part now
Go to Vegas
Play the blackjack
Earn a lucky wad
Find a hot chick
**wait**
Do the best part now
Go to Vegas
Play the blackjack
Earn a lucky wad
Find a hot chick
Do the best part now
Go to Vegas
Play the blackjack
Earn a lucky wad
Find a hot chick
Do the best part now
After every N the match of a string insert another line ( in this case its "wait" )
How best can it be done
I can add a new line after every pattern match
but I want to add a specific line after every Nth pattern match
Like this
sed '/"Find a hot chick"/ a\
wait ' <filename>
Upvotes: 0
Views: 1387
Reputation: 41460
A small variation of grebnekes awk
version
awk '/Find a hot chick/ && !(++i%3) {$0=$0"\n**wait**"}1' file
This will add a new line for every third hit of pattern to the line itself, then print all.
Upvotes: 1
Reputation: 45293
Using sed
sed '/Find a hot chick/{x;s/^/./;/.\{3\}/{s/.\{3\}//;x;s/.*/&\n**wait**/;b};x}' file
Explanation: (it is called "Dot count")
/Find a hot chick/ { # find the key words
x # Exchange the contents of the hold and pattern spaces.
s/^/./ # add one dot in hold space. (such as ..$, ...$ etc)
/.\{3\}/ { # check if there are 3 dots in hold space or not.
s/.\{3\}// # find the third pattern match, clean the dots in hold space.
x # Exchange the contents of the hold and pattern spaces.
s/.*/&\n**wait**/ # add the contents OP asked.
b # b label, Unconditionally branch to label. The label may be omitted, in which case the next cycle is started.
}
x # Exchange the contents of the hold and pattern spaces.
}
If need be done by awk, here is the awk command more straightforward.
awk '/Find a hot chick/{k++;if (!(k%3)){$0=$0 RS "**wait**"}}1' file
Upvotes: 1
Reputation: 207748
Like this:
awk '1;/Find a hot chick/{if(i++==3){print "New line";i=0}}' yourfile
The "1" just does awk's default thing, which is to print, for every line.
Upvotes: 5
Reputation: 14629
With awk
you could do:
#!/usr/bin/awk -f
BEGIN {
counter = 0
}
{
if ( $0 == "Find a hot chick" )
counter++
print
if ( counter == 3 ){
print "**wait**"
counter = 0
}
}
Put it in a file, e.g., file.awk
, and then: ./file.awk your_file
Upvotes: 1