A. Man
A. Man

Reputation: 367

Keep line with specific word and two lines above in Unix log

I have a long log file where I want to keep only the lines with the word 'change' and two lines above this line. how can I do it in Unix?

Upvotes: 0

Views: 370

Answers (1)

Paul T.
Paul T.

Reputation: 4907

It would be easier (I've found) if you can copy the file to Linux (unless you have cygwin or some other similar utility) and use grep. The command would be: grep -B 2 change your.log

That will find the lines with change and include the two previous lines before each change line.

=====

You could get the desired lines in Notepad++, but I've not (yet) found an easy way to do the same, but it is possible. It all depends on what you mean by "long log file", as this effort could take some time:

  1. First, use Search => Mark...
  2. input the 'change' search term
  3. check the 'Bookmark Line' check box
  4. click the 'Mark All' button.

...at this point, all lines that have 'change' will show a bookmark to the left.

  1. Move to the top of the file, if not already there
  2. Press F2 to jump to the next bookmark
  3. At the left, click the two lines above to also appear as bookmarks (make them have the same bookmark indication as the change line)

  4. Repeat steps 6 and 7 for all the change lines, until you have all the "triplets" of bookmarks covered (the line with change and the two previous lines)

  5. After all the bookmarks are set, then do: Search => Bookmark => Remove Unmarked Lines

There may be other ways in Notepad++ that someone might know, but I've used these steps for other needs. F2 is helpful to jump between bookmarks, so this can potentially help speed the process.

Upvotes: 1

Related Questions