grep's Examples

ind text in a file. The grep command searches through many files at a time to find a piece of text you are looking for. grep PATTERN [FILE] grep failed transaction.log The above command will find all of the words in the files that matched the word ‘failed’.

grep ‘failed’ transaction.log

Case insensitive search : The -i option enables to search for a string case insensitively in the given file. It matches the words like “UNIX”, “Unix”, “unix”.

grep -i "UNix" geekfile.txt

 Case insensitive search : The -i option enables to search for a string case insensitively in the given file. It matches the words like “UNIX”, “Unix”, “unix”. 

grep -i "UNix" geekfile.txt

Displaying the count of number of matches : We can find the number of lines that matches the given string/pattern 

grep -c "unix" geekfile.txt

Display the file names that matches the pattern : We can just display the files that contains the given string/pattern.

grep -l "unix" *

Checking for the whole words in a file : By default, grep matches the given string/pattern even if it is found as a substring in a file. The -w option to grep makes it match only the whole words. 

grep -w "unix" geekfile.txt

Displaying only the matched pattern : By default, grep displays the entire line which has the matched string. We can make the grep to display only the matched string by using the -o option. 

grep -o "unix" geekfile.txt

Inverting the pattern match : You can display the lines that are not matched with the specified search string pattern using the -v option. 

grep -v "unix" geekfile.txt

Matching the lines that start with a string : The ^ regular expression pattern specifies the start of a line. This can be used in grep to match the lines which start with the given string or pattern. 

grep "^unix" geekfile.txt

Matching the lines that end with a string : The $ regular expression pattern specifies the end of a line. This can be used in grep to match the lines which end with the given string or pattern.

grep "os$" geekfile.txt

Specifies expression with -e option. Can use multiple times :

grep –e "Agarwal" –e "Aggarwal" –e "Agrawal" geekfile.txt

Print n specific lines from a file:  -A prints the searched line and n lines after the result, -B prints the searched line and n lines before the result, and -C prints the searched line and n lines after and before the result. 

Syntax:

$grep -A[NumberOfLines(n)] [search] [file]  

$grep -B[NumberOfLines(n)] [search] [file]  

$grep -C[NumberOfLines(n)] [search] [file]  

grep -A1 learn geekfile.txt

Match all lines that start with ‘hello’. E.g: “hello there”

grep “^hello” file1

Match all lines that end with ‘done’. E.g: “well done”

rep “done$” file1

Match all lines that contain any of the letters ‘a’, ‘b’, ‘c’, ‘d’ or ‘e’.

grep “[a-e]” file1

Match all lines that do not contain a vowel

grep “[^aeiou]” file1

Match all lines that start with a digit following zero or more spaces. E.g: “ 1.” or “2.”

grep “ *[0-9]” file1

Match all lines that contain the word hello in upper-case or lower-case

grep -i “hello”

Ignore Case Distinctions

grep -i "this" test-file

Count the Number of Patterns

ps -ef | grep -c $USER

Display Line Numbers Containing Matches

cat /etc/passwd | grep -n rubaiat

Find Filenames Using Extensions

ls ~/Music/ | grep ".mp3"

Find Patterns in Compressed Files

gzip test-file

Find Email Addresses

grep '^[a-zA-Z0-9]\+@[a-zA-Z0-9]\+\.[a-z]\{2,\}' test-file

Find Phone Numbers Using Grep

grep '\(([0-9]\{3\})\|[0-9]\{3\}\)[ -]\?[0-9]\{3\}[ -]\?[0-9]\{4\}' test-file

Find URLs From Source Files

grep -E "^(http|https|ftp):[\/]{2}([a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,4})" test-file

Searching Multiple Files

sudo grep -i err /var/log/messages*

Whole Word Search

grep -w is text_file.txt

Check Match Count

grep -c is text_file.txt

Search Sub-directories

grep -r [pattern] *

Inverse Search

grep -v This text_file.txt

Limit grep Output

grep -m[num] [pattern] [file]

Print Exact Lines

grep -x support *.txt

How to use grep recursively

grep -r "192.168.1.5" /etc/

How to use grep to search words only

grep -w "boo" file

Display lines before and after the match

grep -B NUM "word" file


Display lines before and after the match

grep -B 3 "foo" file1

Prints Number of Lines Around Match

The grep’s –C option is similar, but instead of printing the lines that come either before or after the string, it prints the lines in either direction:
ifconfig | grep –C 2 lo

Search Files by Given String

grep –n “main” setup..py

Display lines before and after the match

grep -B 3 "foo" file1

How do I find all files containing specific text on Linux?

grep -rnw '/path/to/somewhere/' -e 'pattern'
-r or -R is recursive,
-n is line number, and
-w stands for match the whole word.
-l (lower-case L) can be added to just give the file name of matching files.
-e is the pattern used during the search

grep a file, but show several surrounding lines?

grep -B 3 -A 2 foo README.txt
grep -C 3 foo README.txt

How do I recursively grep all directories and subdirectories?

grep -r "texthere" .

How to grep (search) committed code in the Git history

git grep <regexp> $(git rev-list --all)
git rev-list --all | xargs git grep <expression>

How to grep (search) committed code in the Git history

git grep <regexp> $(git rev-list --all)
git rev-list --all | xargs git grep <expression>

How can I use grep to show just filenames on Linux?

grep -l

How can I grep recursively, but only in files with certain extensions?

grep -inr --include \*.h --include \*.cpp CP_Image ~/path[12345] |

Negative matching using grep (match lines that do not contain foo)

grep -v
grep --help | grep invert

How can I pipe stderr, and not stdout?

command 2>&1 >/dev/null | grep 'something'

How can I exclude directories from grep -R?

find /dir \( -name foo -prune \) -o \( -name bar -prune \) -o -name "*.sh" -print

Use grep --exclude/--include syntax to not grep through certain files

grep pattern -r --include=\*.cpp --include=\*.h rootdir

How to 'grep' a continuous stream?

tail -f file | grep --line-buffered my_pattern

How to grep Git commit diffs or contents for a certain word

$ git log --grep=word

How can I use grep to find a word inside a folder?

grep -nr 'yourString*' .
-n            Show relative line number in the file
'yourString*' String for search, followed by a wildcard character
-r            Recursively search subdirectories listed
.             Directory for search (current directory)

How do I find files that do not contain a given string pattern?

find .  -not  -ipath '.*svn*' -exec  grep  -H -E -o -c  "foo"  {} \; | grep 0

Colorized grep -- viewing the entire file with highlighted matches

grep --color 'pattern\|$' file
grep --color -E 'pattern|$' file
egrep --color 'pattern|$' file

How can I exclude one word with grep?

grep -v "unwanted_word" file | grep XXXXXXXX
grep -v 'unwanted_word' file

Delete all local git branches

git branch -D `git branch --merged | grep -v \* | xargs`

How can I grep for a string that begins with a dash/hyphen?

grep -- -X

Get line number while using grep

grep -n SEARCHTERM file1 file2 ...

How can I make grep print the lines below and above each matching line? [duplicate]

grep's -A 1 option will give you one line after; 
-B 1 will give you one line before;
-C 1 combines both to give you one line both before and after, -1 does the same.

How can I format my grep output to show line numbers at the end of the line, and also the hit count?

$ grep -in null myfile.txt

2:example two null,
4:example four null,

How do I grep for all non-ASCII characters?

grep --color='auto' -P -n "[\x80-\xFF]" file.xml

How to check if a file contains a specific string using Bash

if grep -q SomeString "$File"; then
  Some Actions # SomeString was found
fi

Fast way of finding lines in one file that are not in another?

diff --new-line-format="" --unchanged-line-format=""  file1 file2
diff --new-line-format="" --unchanged-line-format="" <(sort file1) <(sort file2)

Display filename before matching line

grep 'pattern' file /dev/null
grep -n 'pattern' file /dev/null

Count all occurrences of a string in lots of files with grep

cat * | grep -c string

Highlight text similar to grep, but don't filter out text [duplicate]

$ ack --passthru 'pattern1' file_name

$ command_here | ack --passthru 'pattern1'

How can I find all of the distinct file extensions in a folder hierarchy?

find . -type f | perl -ne 'print $1 if m/\.([^.\/]+)$/' | sort -u

How to suppress binary file matching results in grep [closed]

grep -I -n -H 

-I -- process a binary file as if it did not contain matching data; 
-n -- prefix each line of output with the 1-based line number within its input file
-H -- print the file name for each match

grep without showing path/file:line

grep -hn FOO /your/path/*.bar
-h, --no-filename
-H, --with-filename

What is makeinfo, and how do I get it?

sudo apt-get install texinfo

How to search contents of multiple pdf files?

find /path -name '*.pdf' -exec sh -c 'pdftotext "{}" - | grep --with-filename --label="{}" --color "your pattern"' \;

How to invert a grep expression

ls -R |grep -v -E .*[\.exe]$\|.*[\.html]$

How can I have grep not print out 'No such file or directory' errors?

grep pattern * -s -R -n

How to get the process ID to kill a nohup process?

nohup my_command > my.log 2>&1 &
echo $! > save_pid.txt

Regex (grep) for multi-line search needed [duplicate]

$ grep -Pzo "(?s)^(\s*)\N*main.*?{.*?^\1}" *.c

How to grep a string in a directory and all its subdirectories? [duplicate]

grep -R 'string' dir/
find dir/ -type f -exec grep -H 'string' {} +

How to show only next line after the matched one?

awk '/blah/{getline; print}' logfile

grep output to show only matching file

grep -l
(That's a lowercase L)

Grep regex NOT containing string 

grep "${PATT}" file | grep -v "${NOTPATT}"

Remove blank lines with grep

grep -v -e '^$' foo.txt

PowerShell equivalent to grep -f

Get-Content .\doc.txt | Select-String -Pattern (Get-Content .\regex.txt)

(grep) Regex to match non-ASCII characters?

[^\x00-\x7F]
[[:ascii:]] - matches a single ASCII char
[^[:ascii:]] - matches a single non-ASCII char

Exclude .svn directories from grep [duplicate]

grep --exclude-dir=".svn"

How to concatenate multiple lines of output to one line?

$ grep pattern file | tr '\n' ' '
$ grep pattern file | awk '{print}' ORS='" '

How to remove the lines which appear on file B from another file A?

comm -23 file1 file2

How to get the part of a file after the first line that matches a regular expression

sed -n -e '/TERMINATE/,$p'

How to merge every two lines into one from the command line?

awk 'NR%2{printf "%s ",$0;next;}1' yourFile
sed 'N;s/\n/ /' yourFile

More elegant "ps aux | grep -v grep"

ps aux | egrep '[t]erminal'

List files with certain extensions with ls and grep

ls *.{mp3,exe,mp4}

Grep characters before and after match?

$> echo "some123_string_and_another" | grep -o -P '.{0,3}string.{0,4}'
23_string_and


How to use sed/grep to extract text between two words?

sed -e 's/Here\(.*\)String/\1/'

How to process each output line in a loop?

grep xyz abc.txt | while read -r line ; do
    echo "Processing $line"
    # your code goes here
done

Preserve colouring after piping grep to grep

grep --color=always WORD * | grep -v AVOID

How can I "grep" for a filename instead of the contents of a file? [closed]

$ find | grep "f[[:alnum:]]\.frm"

How to exclude certain directories/files from git grep search

You can put *.dll to .gitignore file then git grep --exclude-standard.

Is it possible to perform a 'grep search' in all the branches of a Git project?

git grep <regexp> $(git rev-list --all)

Checking if output of a command contains a certain string in a shell script

if ./somecommand | grep -q 'string'; then
  echo "matched"
fi

How to grep for case insensitive string in a file?

grep -iF "success..." file1

How do you search for files containing DOS line endings (CRLF) with grep on Linux?

grep -IUr --color "^M"

How can I search for a multiline pattern in a file?

the -M option makes it possible to search for patterns that span line boundaries.
find . -iname '*.py' | xargs pcregrep -M '_name.*\n.*_description'

How can I extract the first two characters of a string in shell scripting?

pax> long="USCAGol.blah.blah.blah"
pax> short="${long:0:2}" ; echo "${short}"
US

Can I grep only the first n lines of a file?

head -10 log.txt | grep <whatever>

How to search a specific value in all tables (PostgreSQL)?

$ pg_dump --data-only --inserts -U postgres your-db-name > a.tmp
$ grep United a.tmp
INSERT INTO countries VALUES ('US', 'United States');
INSERT INTO countries VALUES ('GB', 'United Kingdom');

Grepping a huge file (80GB) any way to speed it up?

LC_ALL=C fgrep -A 5 -B 5 'db_pd.Clients' eightygigsfile.sql

How to grep for two words existing on the same line? [duplicate]

grep "word1" FILE | grep "word2"

Validating IPv4 addresses with regexp

'\b((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)(\.|$)){4}\b'

Is \d not supported by grep's basic expressions? [closed]

echo 1 | grep -P '\d'
# output: 1
echo 1 | grep '[[:digit:]]'
# output: 1

Using sed, how do you print the first 'N' characters of a line?

grep .... | cut -c 1-N
grep ... | sed -e 's/^\(.\{12\}\).*/\1/'

How do you grep a file and get the next 5 lines

grep -A 5 '19:55' file

grep for special characters in Unix

grep -F '*^%Q&$*&^@$&*!^@$*&^&^*&^&' application.log
grep -Fn '*^%Q&$*&^@$&*!^@$*&^&^*&^&' application.log


Grep for literal strings

-F, --fixed-strings       PATTERN is a set of newline-separated fixed strings

how do I use the grep --include option for multiple file types?

grep -r --include=*.html --include=*.php --include=*.htm "pattern" /some/path/


Use grep to report back only line numbers

grep -n "text to find" file.ext | cut -f1 -d:

How to make grep only match if the entire line matches?

grep '^ABB\.log$' a.tmp

git grep by file extensions

git grep res -- '*.js'

How can I grep hidden files?

grep -r search * .[^.]*

How to give a pattern for new line in grep?

grep '^$' file
grep '^[[:space:]]*$' file # include white spaces

How to grep for the whole word

find . | xargs grep -sw 's:text'

Grep not as a regular expression

Escape the $ by putting a \ in front of it.

Show filename and line number in grep output

grep -Hn "search" *
grep -nHo "search" *

How to grep for contents after pattern?

grep 'potato:' file.txt | sed 's/^.*: //'

grep regex whitespace behavior

GNU grep 2.5.4
echo "foo bar" | grep "\s"
   (doesn't match)
GNU grep 2.6.3
echo "foo bar" | grep "\s"
foo bar

grepping using the "|" alternative operator

grep "gene\|exon" AT5G60410.gff

Using sed and grep/egrep to search and replace

egrep -lRZ "\.jpg|\.png|\.gif" . \
    | xargs -0 -l sed -i -e 's/\.jpg\|\.gif\|\.png/.bmp/g'

How to display modified date time with 'find' command?

find /var -maxdepth 2 -type d -exec stat  -c "%n %y" {} \;

Count number of occurrences of a pattern in a file (even on same line)

echo afoobarfoobar | grep -o foo | wc -l

Grep 'binary file matches'. How to get normal grep output? [duplicate]

grep --text
grep -a

Remove empty lines in a text file via grep

grep . FILE
sed -e /^$/d FILE
awk /./ FILE

How to grep the git diff?

-G < regex>

How to grep with a list of words

$ grep -f A B
$ grep -Ff A B
$ grep -wFf A B

How to use grep to get anything just after `name=`?

grep -P '(?<=name=)[ A-Za-z0-9]*' filename

Command line: search and replace in all filenames matched by grep

perl -p -i -e 's/old/new/g' `ack -l searchpattern`

Prevent grep returning an error when input doesn't match

ps -ef | grep bar | { grep -v grep || true; }

Fastest possible grep

find . -type f | parallel -k -j150% -n 1000 -m grep -H -n STRING {}

How to "grep" out specific line ranges of a file

sed '2,4!d' somefile.txt

How to find all file extensions recursively from a directory?

find . -type f -name '*.*' | sed 's|.*\.||' | sort -u

changing chmod for files but not directories

find . -type f -print0 | xargs -0 chmod 644

How to remove leading whitespace from each line in a file

sed "s/^[ \t]*//" -i youfile

Linux find and grep command together

find . -name '*bills*' -exec grep -H "put" {} \;

Using grep and sed to find and replace a string

find /path -type f -exec sed -i 's/oldstr/newstr/g' {} \;

grepping binary files and UTF16

iconv -f utf-16 -t utf-8 file.txt | grep query

Pattern matching digits does not work in egrep?

egrep '[0-9]{7}-[0-9]{10}' file

grep only text files

$ grep -rI "TEXTSEARCH" .

Recursively cat all the files into single file

find data/ -name '*.json' -exec cat {} \; > uber.json

Spider a Website and Return URLs Only

wget --spider --force-html -r -l2 $url 2>&1 \
   grep '^--' | awk '{ print $3 }' \
   grep -v '\.\(css\|js\|png\|gif\|jpg\)$' \
  > urls.m3u

Bash, grep between two lines with specified string

awk '/test1/{f=1} /test2/{f=0;print} f'
awk '/test1/{f=1} f; /test2/{f=0}' 
awk '/test1/,/test2/'

How do I view all ignored patterns set with svn:ignore recursively in an SVN repository?

svn pg -R svn:ignore .
svn propget -R svn:ignore .

Waiting for background processes to finish before exiting script

#!/bin/sh
{ sleep 5; echo waking up after 5 seconds; } &
{ sleep 1; echo waking up after 1 second; } &
wait
echo all jobs are done!


How to match once per file in grep?

grep -ri -m1 --include '*.coffee' 're' . | head -n 2

Redirect stderr to /dev/null

some_cmd 2>/dev/null
find . -type f -name "*.txt" -exec grep -li needle {} +

How to remove the last character from a bash grep output

COMPANY_NAME=`cat file.txt | grep "company_name" | cut -d '=' -f 2 | sed 's/;$//'`

Use grep to find content in files and move them if they match

grep -L -Z -r 'Subject: \[SPAM\]' . | xargs -0 -I{} mv {} DIR

Always include first line in grep

$ grep -E 'COL|pattern' file.csv

Delete a list of files with find and grep

find . -name '*car*' -exec rm -f {} \;
find | grep car | xargs rm -f

Can you mass edit all files returned in a grep?

vim $(grep -rIl 'xg_icon-*' *)

Linux shell script to add leading zeros to file names

for a in [0-9]*.txt; do
    mv $a `printf %04d.%s ${a%.*} ${a##*.}`
done

Grep output with multiple Colors?

tail -f myfwlog | GREP_COLOR='01;36' egrep --color=always 'ssh|$' | GREP_COLOR='01;31' egrep -i --color=always 'drop|deny|$'

How can I check if 'grep' doesn't have any output?

if grep -q $address  /etc/passwd
then 
   echo "OK";
else
   echo "NOT OK";
fi

Unix grep regex containing 'x' but not containing 'y'

^((?!beta).)*alpha((?!beta).)*$

How to do whole-word search similar to "grep -w" in Vim

:s/\<bar\>/baz

Tarballing without Git metadata

find -type f . | egrep -v '\.git|\.log' | xargs tar rvf ~/app.tar

Using grep with regular expression to filter out matches

tail -f logFile | grep -vE 'string one|string two'

It searches for the string pattern in the file by ignoring the case for matching

grep -i assam test

It searches fro the string pattern in the file by ignoring the case and returns the count of the string mentioned.

grep -ic assam test

It displays the file name that matches the string pattern.

grep -l Assam test

grep searches given word in the given file

grep red colors.txt

it searches all files in the current directory for the word red

grep -R red

it gives the number of times the word red is repeated in the colors.txt

grep -c red colors.txt

search the user name 

grep pavani /etc/passwd

search for the user name

grep pavani /etc/passwd

searches for the word in the given text.

grep -F apple colors.txt

gives all the file names in which the word apple is present

grep -l 'apple' *.txt

by -s option we instruct grep command not to print "no file or directory" and permission denied" messages

grep -R -i -s "pavani" /etc/

gives the system congiguration

grep -i 'model' /proc/cpuinfo

DevOpsSchool
Typically replies within an hour

DevOpsSchool
Hi there 👋

How can I help you?
×
Chat with Us