Lesson 6: Searching inside files — grep
Last lesson we read whole files, but a real log can be huge — thousands of lines. When the service goes down you don't want to read it all; you want just the lines with the error. That's what grep is for: it searches a word inside a file and prints only the lines that contain it — like Ctrl+F for th
grep is the terminal's Ctrl+F: you give it a word, and it pulls out only the lines in the file that contain that word, ignoring everything else.
- grep
- Searches a word or phrase inside a file and prints only the lines that contain it. E.g. grep ERROR app.log shows only lines with the word ERROR.
- pattern (the search word)
- What you search for — the word or phrase. In grep it comes first, then the file name: grep <pattern> <file>.
- -i (ignore case)
- grep -i ignores the difference between upper and lower case, so error, ERROR, and Error are all found.
- -n (line numbers)
- grep -n prefixes each matching line with its line number in the file — handy for knowing exactly where it happened.