在每第N个模式匹配后添加一个特定的行.AWK SED你得到的任何东西

时间:2014-02-03 22:13:55

标签: shell search sed awk grep

我有一个像这样的文件

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

我想在“寻找一个小鸡”的第3h比赛后添加一条线等待

所以上面应该阅读。

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

每N个字符串匹配后插入另一行(在本例中为“等待”)
如何才能做到最好 我可以在每个模式匹配后添加一个新行 但是我希望在每个第N个模式匹配后添加一个特定的行 喜欢这个

sed '/"Find a hot chick"/ a\
    wait ' <filename>

4 个答案:

答案 0 :(得分:5)

像这样:

awk '1;/Find a hot chick/{if(i++==3){print "New line";i=0}}' yourfile

对于每一行,“1”只执行awk的默认操作,即打印。

答案 1 :(得分:1)

使用awk,您可以:

#!/usr/bin/awk -f
BEGIN {
  counter = 0
}

{
  if ( $0 == "Find a hot chick" )
    counter++
  print
  if ( counter == 3 ){
    print "**wait**"
    counter = 0
  }
}

将其放入文件中,例如file.awk,然后:./file.awk your_file

答案 2 :(得分:1)

使用sed

sed  '/Find a hot chick/{x;s/^/./;/.\{3\}/{s/.\{3\}//;x;s/.*/&\n**wait**/;b};x}' file

说明:(它被称为“点数”)

/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.
}

如果需要通过awk完成,这里的awk命令更直接。

awk '/Find a hot chick/{k++;if (!(k%3)){$0=$0 RS "**wait**"}}1' file

答案 3 :(得分:1)

grebnekes awk

的一小部分
awk '/Find a hot chick/ && !(++i%3) {$0=$0"\n**wait**"}1' file

这将为每行第三次模式添加一个新行,然后打印所有。