Grep demo
The grep command is a powerful command-line utility used to search for specific patterns in text and then print the lines that match those patterns. The name grep is an acronym for "globally search for a regular expression and print it out".
Let's work through some exercises by Sundeep at
github.com/learnbyexample
Sample.txt
Hello World
Hi there
How are you
Just do-it
Believe it
banana
papaya
mango
Much ado about nothing
He he he
Adios amigo
Code.txt
fruit = []
fruit[0] = 'apple'
def fruit():
print('banana')
1. Display lines containing an .
grep 'an' sample.txt
banana
mango
2. Display lines containing do as a whole word.
grep -w 'do' sample.txt
Just do-it
3. Lines that meet these conditions:
- he matched irrespective of case
- eitherWorld or Hi matched case senstively
$ grep -i 'he' sample.txt | grep -e 'World' -e 'Hi'
Hello World
Hi there
4. Lines containing fruit[0] literally.
$ grep -F 'fruit[0]' code.txt
fruit[0] = 'apple'
5. Display only the first two matching lines containing t from the sample.txt input file.
$ grep -m2 't' sample.txt
Hi there
Just do-it
6. Display only the first three matching lines that do not containhe
$ grep -m3 -v 'he' sample.txt
Hello World
How are you
7. Lines that contain do along with line number prefix.
$ grep -n 'do' sample.txt
6:Just do-it
13:Much ado about nothing
8. Count the number of times the string he is present, irrespective of case.
$ grep -io 'he' sample.txt | wc -l
5
9. Count the number of empty lines
$ grep -cx '' sample.txt
4
10. For both input files - display matching lines based on the search terms (one per line) present in the terms.txt file. Results should be prefixed with the corresponding input filename.
terms.txt
are
not
go
fruit[0]
$ grep -Ff terms.txt sample.txt code.txt
sample.txt:How are you
sample.txt:mango
sample.txt:Much ado about nothing
sample.txt:Adios amigo
code.txt:fruit[0] = 'apple'
to be continued....
Sources
-
github.com/learnbyexample/learn_gnugrep_ripgrep/blob/master/exercises/Exercise_solutions.md
-
redhat.com/en/blog/how-to-use-grep