Unix

GREP command in Unix/Linux with examples

grep – Global Regular Expression Parser

It is used to search data in one/more files.
Command 1: Search pattern in file
- grep hello file.txt
- grep sai file.txt file2.txt

Command 2: Search pattern in current folder with all txt extensions.
grep 1000 *.txt

Command 3: Search data in all files in current folder
grep 1000 *.*

Command 4: Search ignoring case[-i]
grep "Sai" file.txt (case sensitive by default)
grep -i "Sai" file.txt

Command 5: Display line number [-n]
grep -n "124" result.txt

Command 6: Get only filenames in which data exists[-l]
grep -l "100" *.*

Command 7: Search exact word [-w]
grep -w Sai file.txt

Command 8: Search lines of files which does not have that data(reverse of search)[-v]
grep -v "1000" file.txt

Command 9:
- Get one record before the search
grep -B 1 "Msd" file.txt
- Get one record after the search
grep -A 1 "Msd" file.txt
- Get one record before and after search
grep -C 1 "Msd" file.txt
Command 10: Display no.of matches/Cound matches[-c](lower case)
grep -c "1000" file.txt

Command 11: Search multiple context in one command [-e]
grep -e "sai" -e "kumar" file.txt

Command 12: egrep – Extended GREP

egrep 'Msd|Sai' file.txt

Share This Post

An Ambivert, music lover, enthusiast, artist, designer, coder, gamer, content writer. He is Professional Software Developer with hands-on experience in Spark, Kafka, Scala, Python, Hadoop, Hive, Sqoop, Pig, php, html,css. Know more about him at www.24tutorials.com/sai

Lost Password

Register

24 Tutorials