在匹配的模式上方添加一行文本

时间:2018-02-08 07:54:28

标签: bash sed grep

我有很多.cpp文件。说 tes1.cpp

 example
//commented
 abc
 def

test2.cpp

efg

test3.cpp

def
efg

我需要编写一个脚本,

 find which file has abc pattern, 
  if found need to find if it has //commented pattern, 
    if it is found then find if //additional text,
        if not found then add a line of text //additional comment above //commented 

输出文件应该是, test1.cpp

example
//additional comment
//commented
abc
def

我试过

if grep -Erl '\babc\b' *; then
   if grep "//commented" ; then
   echo "Already updated"
   else
  sed '\/\/ commented /i\// additional comment' 
  fi
fi

但执行挂起。我该怎么做?

编辑: 编辑命令

grep -Erl '\babc\b' * | xargs sed -i '/ commented /i \// additional comment'

但它不检查文件是否已有//其他评论模式

3 个答案:

答案 0 :(得分:1)

在awk中:

$ awk 'BEGIN{RS="";FS=OFS="\n"}/abc/{for(i=1;i<=NF;i++)if($i~/\/\//)$i="//addtional comment\n" $i}1' file
 example
//addtional comment
//commented
 abc
 def

说明:

awk '
BEGIN {
    RS=""                                 # record changes at first empty line
    FS=OFS="\n"                           # field separator is a newline
}
/abc/ {                                   # if record has abc
    for(i=1;i<=NF;i++)                    # iterate all fields
        if($i~/\/\//)                     # at line with comment
            $i="//addtional comment\n" $i # add the addition
}1' file                                  # print

它位于////additional comment的行之前。您可以根据自己的喜好调整if中的正则表达式。此脚本当时只处理一个文件。

答案 1 :(得分:0)

sed的:

grep -L ' additional comment' * | 
xargs grep -Erl '\babc\b' | 
xargs sed -i '/ commented /i \// additional comment'

这很好。

答案 2 :(得分:0)

这可能适合你(GNU sed):

sed -ri -e '/abc/{:a;i//additional comments\n//commented' \
 -e 'b};N;//{:b;\#//commented#{i//additional comments' \
 -e 'b};P;s/.*\n//;ba};N;//{\#^//additional comment#{p;d};P;s/[^\n]*\n//;bb};P;D' file

如果一行包含abc,则插入两行必填文本。否则,请阅读下一行,如果这包含abc,请检查第一行是否开始//commented,如果是,请插入所需文本的第一行并打印另外两行,否则打印第一行,删除它,然后将该行视为第一个。否则,请检查abc等的第三行