grep based on pattern in a line and print the column before that

$ cat file.log
Message Number = [ ]: Sending message 10:50:16^|^reqhdr.dummyid^=^02^|^reqhdr.timezone^=^GMT+05:30^|^DUMMYREQUEST^=^BH||||||||||||||||||$BD|OL|C|V||DummyAcctNo|02||24/12/2011|ST_DDM|DDM||||||||reqUUID110612105016$BT||||||||||||||||||$] Length [472]

I have the above line in the file.log

My requirement is to find in which column the reqUUID110612105016$BT is present(column delimiter is | ) and i need to find the column number of DummyAcctNo field and display the value in that column.

The clue here is there is 12 columns inbetween reqUUID110612105016$BT and DummyAcctNo column with delimiter as |

In simple words, The only input i know is reqUUID110612105016$BT and i need to display the output as DummyAcctNo.

Pl help. I have no idea what to do.

awk -F'|' '{for(i=1;i<=NF;i++){ if($i == "reqUUID110612105016$BT") { print $(i-13) } }}' file.log
1 Like

Thanks for the script. Its working fine. I need to implement small modification in the script, but it's not working :frowning:

I need to pass reqUUID110612105016 alone as a variable to the above script. I have tried the below script.

$sh
$x=reqUUID110612105016
$ cat File.log|awk -F'|' '{for(i=1;i<=NF;i++){ if($i == "'$x'$BT") { print $(i-13) } }}' 

But its not working :wall:

Pl help me in implementing this.

Hi, try:

awk -F'|' '{for(i=1;i<=NF;i++) if($i == x "$BT") print $(i-13)}' x=reqUUID110612105016

or

var=reqUUID110612105016
awk -F'|' '{for(i=1;i<=NF;i++) if($i == x "$BT") print $(i-13)}' x="$var"

Thanks a lot Scrutinizer. The code works like charm for my requirement :slight_smile: