Thursday, 18 June 2020

Learn grep command by examples



grep
command can be used to search the named input FILEs, or standard input if no files are named, for lines containing a match to the given PATTERN. By default, grep prints the matching lines.

Example usages.

Suppose you have these files:


 file.txt         file2.txt        
word1
word2
word3
hello world!
word5
word6
word1
word2
hello friend!
word4
word5
word6 


  • Print the lines containing "hello" from file.txt:

$ grep 'hello' file.txt
hello world!


  • Search in multiple files:

$ grep 'hello' file.txt file2.txt
file.txt:hello world!
file2.txt:hello friend!


  • For multiple strings:

$ grep 'hello world' file.txt
hello world!


  • Alternative commands:

$ cat file.txt | grep 'hello'
$ grep -i 'hello' file.txt


  • Search recursively for a string inside files in directory:

$ grep -r "hello" /home/abc
/home/file.txt:hello world!


  • Same result, without showing file name:

$ grep -h -R "hello" /home/abc
hello world!


  • Print the number of lines in file, containing the string:

$ grep -c 'hello' file.txt
1


  • Print also the line number in file, where the string is found:

$ grep -n 'hello' file.txt
4:hello world!


  • Invert match: print only those lines that do not contain the given word:

$ grep -v 'hello' file.txt
word1
word2
word3
word5
word6


  • List all the files with .txt extension containing the string:

$ grep -l 'hello' *.txt
file.txt


  • Search exactly for a string inside a file:
$ grep -x 'hello world' file.txt

(give no results)

$ grep -x 'hello world!' file.txt
hello world! 


  • Use colors to highlight matches:

$ grep --color hello file.txt
hello world!




No comments:

Post a Comment