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

时间:2019-10-16 13:51:57

标签: bash fedora

我正在运行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

3 个答案:

答案 0 :(得分:1)

如果您对awk没问题,请尝试按照以下步骤操作

awk -v var="$myVar" '/\[test\]/ && ++count==2{print var ORS $0;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 $0            ##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.

答案 1 :(得分:0)

您可以这样做。

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

答案 2 :(得分:0)

您可以使用sed执行此操作。 您的输入在firstfile.txt中 结果在secondfile.txt中

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