6

I have something like grep "keyword" -B 3 log. It shows a lot of results, like:

some trash
[GET] /orders/42
one more trash
keyword and useful info

[GET] /orders/43
some trash
one more trash
keyword and useful info

some trash
one more trash
[GET] /orders/44
keyword and useful info

How can I save each grep result into a separate file 42, 43, 44 with keyword and useful info line. Each grep result is guaranteed have one [GET] /orders/[0-9]* line.

  • Yes some lines between keyword and id exists (one, two or zero). But no overlap. – Stepan Loginov Jul 14 '16 at 11:20
  • 1
    Please edit your question and show us an example of your input file and your desired output. We can probably give you a better solution than grep but we can't if we don't know your data. – terdon Jul 14 '16 at 11:30
  • Do you actually need those "trash" lines or do you only need the lines with keyword, each one saved in a file named after the value of the preceding unique_id ? – don_crissti Jul 14 '16 at 11:40
  • only line with keywords – Stepan Loginov Jul 14 '16 at 11:41
8
awk -v keyword=keyword -F/ '/\[GET\]/ { id=$NF; next } $0 ~ keyword { print $0 > id }' log
  • Maybe you missed $ before id? { print $0 > id } to { print $0 > $id } – Stepan Loginov Jul 14 '16 at 12:28
  • Oh no, it's ok. Sorry – Stepan Loginov Jul 14 '16 at 12:30

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.