Ubuntu – How to include information in the line above when searching for a pattern in a line

command linegreptext processing

I need to differentiate between first image and second image scenarios when retrieveing information using grep. They both are created_at but one is for image and one is for tweet. All the ones for tweet have a }, in the line above so I thought I could use that information however I am not sure how I could do this.

Here's the grep I use:

grep -wirnE 'Wed Oct 19 2(1:[0-5][0-9]:[0-5][0-9]|2:([0-2][0-9]:[0-5][0-9]|30:00)) .* 2016' *

enter image description here

enter image description here

Best Answer

You can use the options -A1 and -B1 to let grep print the line after (-A) and before (-B) the matching line. Try the following command line,

grep -B1 created_at log-file|grep -A1 '^}'|grep created_at

I tested with the following input file named log-file

asdf
qwerty
...
},
"created_at" "date-with-near-}"
zxcv
some other string
"created_at" "date-without-}"
...

Testing sequence

$ grep -B1 created_at log-file
},
"created_at" "date-with-near-}"
--
some other string
"created_at" "date-without-}"

$ grep -B1 created_at log-file|grep -A1 '^}'
},
"created_at" "date-with-near-}"

$ grep -B1 created_at log-file|grep -A1 '^}'|grep created_at
"created_at" "date-with-near-}"
Related Question