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.

4
  • Yes some lines between keyword and id exists (one, two or zero). But no overlap. Commented Jul 14, 2016 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. Commented Jul 14, 2016 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 ? Commented Jul 14, 2016 at 11:40
  • only line with keywords Commented Jul 14, 2016 at 11:41

1 Answer 1

8
awk -v keyword=keyword -F/ '/\[GET\]/ { id=$NF; next } $0 ~ keyword { print $0 > id }' log
2
  • Maybe you missed $ before id? { print $0 > id } to { print $0 > $id } Commented Jul 14, 2016 at 12:28
  • Oh no, it's ok. Sorry Commented Jul 14, 2016 at 12:30

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.