grep matches patterns. it uses regex to match patterns
grep expression file
Example
grep hello helloworld.txt
will searhc for hello in the file helloworld.txt
^
matches all the lines that begin with hello. ^
goes at the beginning of the search expression.
grep ^hello helloworld.txt
$
will give you all the lines that end with your search expression. $
goes at the end of the search expression.
grep hello$ helloworld.txt
will give you all the lines that end with hello in your helloworld.txt file.
-c
gives you count. For example:
grep -c ^hello helloworld.txt
grep -c hello$ helloworld.txt
will give you the amount of lines that start with hello and the amount of lines that end with hello.
By default, grep
is case-sensitive. -i
gives you case-insensitive results.
select non-mathcing lines
egrep -vi 'hello|world' file.txt
will find all lines that do not contain hello or world.
[]
let you search for a character. For example:
grep [h] in helloworld.txt
will output all the h instances in helloworld.txt. You can also search for multiple characters, like so:
grep [hpokj] hellowolrd.txt
will return all the lines that have our given characters.
^
[ ] and [ ]$
will output lines that begin ^
or end $
with our specified characters. For example:
grep ^[hpokj] hellowolrd.txt
grep [hpokj]$ hellowolrd.txt
grep [a-g] file.txt
grep [1-9] file.txt
grep -f grepinput file.txt
OR
grep -f inputFile.txt fileToSearch.txt
list files that match our pattern in the file name or somewhere within in the files.
grep -lr cron /etc/
By default, grep outputs lines that have your pattern. -l
is so it output file names of files that have that pattern, whether in the file name or in the file content.
grep is great for parsing websites. For example, you can download a website and get only image links from it.
allows use of extended regex.
egrep -i 'hello.*world' file.txt
will search for hello world case-insesitively
egrep -i 'hello|world' file.txt
will search for hello or world case-insesitively
You can pipe multiple grep commands to get selective results
egrep 'hello|world' file.txt | grep -v jeff
will find all the lines that contain either hello or world but do not contain jeff
special characters don’t have any meaning. hello$
will search for lines with hello$ and not every line that ends with hello. The results are literally what you asked for.
Good in cases where you have to search a lot of files. since youre not using regex, there’s less cpu usage. fgrep finishes much faster.