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



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

asdf
asdf
[test]
asdasd
[test]

asdasd

我想在第二次出现 [test] 之前插入"行到插入">

到目前为止,我有

myVar="lineToInsert"
sed  '/[test]/i'$myVar inputTest > test.txt

问题是这个在[测试]的每个occouring之前插入"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 $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.

你可以这样做。

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

您可以使用 sed 执行此操作。 您的输入在第一个文件中.txt 结果在第二个文件中.txt

sed 's/[test]/[test]nYOURSTRINGn/g' firstfile.txt > secondfile.txt

最新更新