Print line after nth occurrence of a match
awk -v n=3 '/<Car>/ && !--n {getline; print; exit}'
Or:
awk '/<Car>/ && ++n == 3 {getline; print; exit}'
To pass the search pattern as a variable:
var='<car>'
PATTERN="$var" awk -v n=3 '
$0 ~ ENVIRON["PATTERN"] && ++n == 3 {getline; print; exit}'
Here using ENVIRON
instead of -v
as -v
expands backslash-escape sequences and backslashes are often found in regular expressions (so would need to be doubled with -v
).
GNU awk
4.2 or above lets you assign variables as strong typed regexps. As long as its POSIX mode is not enabled (for instance via the $POSIXLY_CORRECT
environment variable, you can do:
# GNU awk 4.2 or above only, when not in POSIX mode
gawk -v n=3 -v pattern="@/$var/" '
$0 ~ pattern && ++n == 3 {getline; print; exit}'
Here's a perl one:
perl -ne 'print && exit if $c==3; $c++ if /<Car>/;' file
With GNU grep
, you can also parse its output like:
grep -A 1 -m 3 '<Car>' file | tail -n 1
From man grep
:
-A NUM, --after-context=NUM
Print NUM lines of trailing context after matching lines.
Places a line containing a group separator (--) between
contiguous groups of matches.
-m NUM, --max-count=NUM
Stop reading a file after NUM matching lines.
With GNU awk
you can do:
gawk -v RS='</Car>' 'NR==3 && $0=$2' inputFile