I am currently facing a challenging script where I need to grep for the following 700e10 for example under the column partnum and find/grep for "rstcb" above that line. The problem is that it is not a fixed number of lines above the grep for "rstcb".

enter image description here

Steps to get this Step 1: Select hex(partnum) from systables where tabname = "stocks"

output for example: 0x00700e10

Step 2: (informix) Run onstat -g opn | grep -i 700e10

Step 3: You will get the the above text from image for example

I would like to include a grep that can search for the text rstcb above the initial result from step 2. Once I have that I would like to awk '{print $2}' the number 700000036d048e8

  • i think a python iterator will be a cleaner solution to use – Ijaz Ahmad Khan Aug 25 '16 at 10:31
  • 5
    Also, please don't post images of text. The snippet in the image would have been a useful test input for anyone going to answer. – ilkkachu Aug 25 '16 at 10:38
  • You mention that it's not a fixed number of lines between rstcb and 700e10, but is there a maximum? – JigglyNaga Aug 25 '16 at 12:43
  • Sorry for the image, I am a first time user. I will make sure I do it right the next time. The maximum number of lines can also vary, depending on the number of open locks a user or users have on a single table. – Christopher Karsten Aug 26 '16 at 12:22

If I got the requirement right, a brief awk should do it:

$ cat > test
rstcb 999999999999
rstcb 700000000123
foo bar doo partnum
1 2 3 4
5 6 7 7001e0

$ awk -vkey=7001e0  '/^rstcb/ {val=$2; next} $4 == key {print val; exit}' test   

This saves the second field of any line starting with rstcb, and prints the saved value (the last one) if a line is met where the fourth field matches 7001e0 or whatever key was set to on the command line.

The next in the first code block skips the second test, and the exit is there to stop after the first match. If you remove that, you get multiple hits, but they might be from the same rstcb line.


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.