Trying to grep lines of output for a string, then return $3 (column 3) + that found string

Viewed 58

I have many lines of text in a file - EACH line in this format:

blah blah filename1 blah blah blah blah text { ANY TEXT ANY HERE } blah blah blah

For any lines that have 'text { whatever }' Im trying to get the 3rd column ($3) appended in front of the found text 'text { whatever }'

So I have the last part working, I just need to grab that $3:

cat data.txt | grep -oP 'text {/*?}'

*UPDATED for more accurate scenario Here is the actual lines of code its scanning (Its an F5 load balancer config):

ltm virtual www.testapp.com_80 { creation-time 2021-09-11:00:01:39 destination 10.105.34.20:http ip-protocol tcp last-modified-time 2021-09-11:19:56:16 mask 255.255.255.255 profiles { http { } tcp { } } rules { HTTP_to_HTTPS_Redirect } source 0.0.0.0/0 source-address-translation { type automap } translate-address enabled translate-port enabled vs-index 14 }

ltm virtual www.testapp2.com_443 { creation-time 2022-02-17:05:06:52 destination 10.105.34.23:https ip-protocol tcp last-modified-time 2022-02-17:05:06:52 mask 255.255.255.255 profiles { http { } tcp { } } rules { HTTP_to_HTTPS_Redirect } source 0.0.0.0/0 translate-address enabled translate-port enabled vs-index 20 }

These are just two lines that are representative of a HUUGE config file.

I just need the $3 (3rd column) from that line (VIP website name which is present in each line) printed with the irules listed " rules { text in here }"

So for those two lines... I am looking for output that looks like:

www.testapp.com_80 { HTTP_to_HTTPS_Redirect }
www.testapp2.com_443 { HTTP_to_HTTPS_Redirect }

Thanks for the assist!

2 Answers
$ awk 'match($0,/(^| )rules *{[^}]*}/){ x=$3; $0=substr($0,RSTART,RLENGTH); $1=x; print }' file
www.testapp.com_80 { HTTP_to_HTTPS_Redirect }
www.testapp2.com_443 { HTTP_to_HTTPS_Redirect }

With sed you could try following code. Written and tested in GNU sed with its -E option to enable ERE regex, with your shown samples. Using sed's capability of using capturing groups to store matched values into temp buffer memory which could be used later on while performing substitution in sed.

Here is the Online demo for used regex in below sed code.

sed -E 's/^[^[:space:]]+[[:space:]]+[^[:space:]]+[[:space:]]+([^[:space:]]+) .*(\{[^}]*}).*/\1 \2/' Input_file
Related