在文件中第二次出现单词之前插入文本

Inserting text before the second occurrence of a word in file

我是 运行 Fedora 30,想写一个 bash 脚本。我有一个包含测试数据的文件

asdf
asdf
[test]
asdasd
[test]


asdasd

我想在 [test]

第二次出现之前插入 "lineToInsert"

到目前为止我有

myVar="lineToInsert"

sed  '/\[test\]/i'$myVar inputTest > test.txt

问题是在每次 [test] 出现之前插入 "lineToInsert"。结果

asdf
asdf
lineToInsert
[test]
asdasd
lineToInsert
[test]


asdasd

我要的是这个

asdf
asdf
[test]
asdasd
lineToInsert
[test]


asdasd

如果您对awk

满意,请尝试关注
awk -v var="$myVar" '/\[test\]/ && ++count==2{print var ORS [=10=];next} 1' Input_file

说明: 在此处添加对上述代码的说明。

awk -v var="$myVar" '         ##Starting awk program here, defining var variable of awk which has value of myVar which is a shell variable.
/\[test\]/ && ++count==2{     ##Checking condition if a line has test in it and count is 2 then do following.
  print var ORS [=11=]            ##Printing variable var then ORS and current line value here.
  next                        ##next will skip all further statements from here.
}                             ##Closing BLOCK for condition here.
1                             ##1 will print edited/non-edited current line.
' Input_file                  ##Mentioning Input_file name here.

你可以做到这一点。

myVar="lineToInsert"
sed -e '/\[test\]/i '"${myVar}" inputTest

您可以使用 sed 来完成此操作。 您的输入在 firstfile.txt 结果在 secondfile.txt

sed 's/\[test\]/\[test\]\nYOURSTRING\n/g' firstfile.txt > secondfile.txt