Hone

Lessons · Terminal · finding the lines that match

Finding lines

grep word file prints the lines that contain the word. -i ignores case, -n adds line numbers, -r searches a whole folder, -c counts.

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

grep is how you find where something lives in a codebase you did not write, and which lines of a log mention the error.

How to think about it

Start with the plainest grep. Add -i when case might differ, -n when you will open the file at that line, -r when you do not know which file.

Worked example

printf 'INFO start\nError: disk\nerror again\n' > log.txt
A small log.
grep -i error log.txt
Both error lines, whatever their case.
grep -n -i error log.txt
The same lines with their numbers: 2 and 3.
grep -c -i error log.txt
2: the count.

Your turn

Find TODO in every file under src, with line numbers.

grep  TODO src/

The trap

grep with an unquoted pattern that has a space or a star. Quote the pattern so the shell hands it over whole.

Practise finding the lines that match on HoneA question on it now, a coding challenge where there is one, and it is remembered for review. Free, no email needed.