Hone

Lessons · Terminal · grep -n: somewhere to go back to

Somewhere to go back to

-n prefixes each match with its line number and a colon, which is the shape every editor knows how to open.

Hone is a place to practise programming. This is one of its lessons, written out in full and free to read without an account.

What it is for

Finding the line is half the job; getting to it is the other half.

How to think about it

Use -n when grep is reading the FILE. In the middle of a pipeline the numbers are positions in the stream, not the file.

Worked example

grep -n 500 access.log
Lines 4 and 6, with the numbers to jump to.
grep -n 500 access.log | cut -d: -f1
Just the numbers.
cat access.log | grep -n 500
The same numbers here only because nothing filtered first.

Your turn

Show which line number matched.

grep  log app.log

The trap

Put a filter before it and the numbering restarts against whatever survived, which is almost never what you wanted to write down.

Practise grep -n: somewhere to go back to on HoneA question on it now, a coding challenge where there is one, and it is remembered for review. Free, no email needed.