🎓 A1Learner
🔍
0 of 50 lessons completed

Shell Searching Inside Files

Searching inside a file means looking for lines that hold a word. The grep command prints every line that matches the word.

Find a word

grep prints the line in notes.txt that holds milk.

grep "milk" notes.txt

Ignore case

grep -i finds Buy milk, even though BUY is in upper case.

grep -i "BUY" notes.txt

Show line numbers

grep -n shows that apples is on lines 1 and 4.

grep -n "apples" shopping.txt

Find a word in a table

grep prints the two rows in data.csv that hold Leeds.

grep "Leeds" data.csv

Example

grep -n "apples" shopping.txt
grep -i "CALL" notes.txt

Key points

  • grep: a command that finds lines that match a word.
  • Give grep a word and a file name, and it prints the matching lines.
  • Use -i to make grep ignore upper and lower case.
  • Use -n to show the line number of each match.
  • grep prints nothing when no line matches.

In this example, grep -n prints the two lines in shopping.txt that hold apples, with their line numbers. Then grep -i finds Call Ana, even though the search word is in upper case.

Try it Yourself

Edit the code, then press Run.

Running is simulated

Exercise

Which command finds matching lines and shows their line numbers?