- Search for a specific string in a file:
grep “searchstring” file.txt
3. Search for a string in all files in a directory:
grep -r “searchstring” directory/
4. Search for a string in all files with a certain file extension in a directory:
grep -r “searchstring” directory/*.txt
5. Search for a string in all files in the current directory and its subdirectories:
grep -r “searchstring” .
6. Search for a string in all files except binary files:
grep -r “searchstring” — exclude-binary-files
7. Search for a string in a case-insensitive manner:
grep -i “searchstring” file.txt
8. Search for a string and display the line number:
grep -n “searchstring” file.txt
9. Search for a string and display the surrounding lines:
grep -C 2 “searchstring” file.txt
10. Search for a string and display the number of matches:
grep -c “searchstring” file.txt
11. Search for a string and exclude certain lines:
grep “searchstring” file.txt | grep -v “excludestring”
12. Search for a string and only display the matching portion of the line:
grep -o “searchstring” file.txt
13. Search for a string and only display the file name:
grep -l “searchstring” directory/*
14. Search for a string and only display the file names that do not contain the string:
grep -L “searchstring” directory/*
15. Search for a string and include the file name in the output:
grep -H “searchstring” file.txt
16. Search for a string and exclude certain directories:
grep -r “searchstring” — exclude-dir=directory-to-exclude .
17. Search for a string and display the lines that do not contain the string:
grep -v “searchstring” file.txt
18. Search for a string and display the lines that contain the string and the lines immediately following them:
grep -A 2 “searchstring” file.txt
19. Search for a string and display the lines that contain the string and the lines immediately preceding them:
grep -B 2 “searchstring” file.txt
20. Search for a string in a compressed file:
zgrep “searchstring” file.gz
21. Search for a string in a specific column of a file:
cut -d ‘,’ -f 2 file.txt | grep “searchstring”