I have a variable input file which could be formatted as below.
text1 valueA valueN valueB
text2 valueX
text1 valueC valueN valueD
text2 valueX
text1 valueE valueM valueF
text1 valueG valueM valueH
text1 valueI valueN valueJ
text2 valueX
text1 valueK valueO valueL
text1 valueP valueO valueQ
text1 valueR valueN valueS
text1 valueT valueM valueU
I only want to print text1 valueA valueN valueB if text2 valueX exists underneath the previous row. For example, the output should be:
text1 valueA valueN valueB
text2 valueX
text1 valueC valueN valueD
text2 valueX
text1 valueI valueN valueJ
text2 valueX
I also need to be able to match part of valueX. Let's say valueX=a.b.c.d-e, I need to match a.b.
myvariable=a.b.
echo $myvariable
a.b.
Update: Apologies for the unclear input data... I asumed I could match partial text, but I was wrong.
So if the data looked like this:
text1 valueA valueN valueB
text2 a.b.c.d-e
text1 valueC valueN valueD
text2 a.b.c.d-e
text1 valueE valueM valueF
text1 valueG valueM valueH
text1 valueI valueN valueJ
text2 a.b.c.d-e
text1 valueK valueO valueL
text1 valueP valueO valueQ
text1 valueR valueN valueS
text1 valueT valueM valueU
How would you match, for example, a.b., if val=a.b.
echo $val
a.b.
Here is one in awk:
$ awk '$0=="text2 valueX"{print p ORS $0}{p=$0}' file
Output:
text1 valueA valueN valueB
text2 valueX
text1 valueC valueN valueD
text2 valueX
text1 valueI valueN valueJ
text2 valueX
Explained:
$ awk '
$0=="text2 valueX" { # if record is a match
print p ORS $0 # print previous buffered record and current
}
{
p=$0 # buffer record for next round
}' file
Updated update with updated data:
As . is a regex metachar it needs to be escaped at input to avoid matching with, for example, abbb:
$ awk -v s="a\\\.b\\\." '$0~s{print p ORS $0}{p=$0}' file
Output now:
text1 valueA valueN valueB
text2 a.b.c.d-e
text1 valueC valueN valueD
text2 a.b.c.d-e
text1 valueI valueN valueJ
text2 a.b.c.d-e
Try this:
awk 'NR>1&& $0 == "text2 valueX"{print a"\n"$0} {a=$0}' input.txt
Note that this scripts prints something only if the current line exactly matches 'text2 valueX'.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With