BSD
BSD

Reputation: 13

Line fetching using awk command

The below command is used to fetch the Nth line "AFTER" a pattern match, when n is a positive number.

But the same command does not work to fetch the Nth line "BEFORE" a pattern match, when I give n as a negative number. Could you help with this?

awk /pattern_to_match/{x = NR + n}NR == x file_to_search

Thanks, BSD

Upvotes: 1

Views: 125

Answers (2)

Akshay Hegde
Akshay Hegde

Reputation: 16997

Something like this may help

tac file_to_search | awk '/pattern_to_match/{x = NR + n}NR == x'

or

awk '{arr[FNR]=$0} /pattern_to_match/{x=FNR-3;if(x in arr){ print arr[x]; exit}}'

Examples:

$ seq 10
1
2
3
4
5
6
7
8
9
10

$ seq 10 | tac | awk '/^7/{x = NR + 3}NR == x'
4

$ seq 10 | awk '{arr[FNR]=$0} /^7/{x=FNR-3;if(x in arr){ print arr[x]; exit}}'
4

Upvotes: 1

drewster
drewster

Reputation: 6090

grep -B N 'pattern_to_match' file_to_search | head -1

Replace N with the number Nth line before the match that you want.

Example: File "a" contains:

hello
there
how
are
you?

Running grep -B 2 "are" a | head -1 returns there.

Possible issue: If there are not N rows prior to the match, the 1st row of the file will be returned.

Upvotes: 3

Related Questions