Wednesday, January 5, 2022

[SOLVED] Inserting text before the second occurrence of a word in file

Issue

I'm running Fedora 30 and want to write a bash script. I have a file with test data

asdf
asdf
[test]
asdasd
[test]


asdasd

i want to insert "lineToInsert" before the second occurrence of [test]

So far i have

myVar="lineToInsert"

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

The problem is that this insert "lineToInsert" before every occourrence of [test]. Resulting in

asdf
asdf
lineToInsert
[test]
asdasd
lineToInsert
[test]


asdasd

What i want is this

asdf
asdf
[test]
asdasd
lineToInsert
[test]


asdasd

Solution

Could you please try following if you are ok with awk

awk -v var="$myVar" '/\[test\]/ && ++count==2{print var ORS $0;next} 1' Input_file

Explanation: Adding explanation for above code here.

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.


Answered By - RavinderSingh13