Search for a word in a file
If you have a file called cloudhouse.txt and you want to find all lines containing the word Python, you can use:
grep "grep" cloudhouse.txt
💡 None of these worked? Skip the guesswork.
Get Expert Help →Commonly Used grep Options
The -i option enables to search for a string case insensitively in the given file. It matches the words like "grep", "Grep", "gRep".
grep -i "Grep" geekfile.txt
- Displaying the Count Matches Using grep
We can find the number of lines that matches the given string/pattern
grep -c "grep" clouhouse.txt
We can just display the files that contains the given string/pattern.
grep -l "grep" *
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 "grep" cloudhouse.txt
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 "grep" cloudhouse.txt
To show the line number of file with the line matched.
grep -n "grep" cloudhouse.txt
You can display the lines that are not matched with the specified search string pattern using the -v option.
grep -v "grep" cloudhouse.txt
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 "^grep" cloudhouse.txt
Conclusion
The grep command is a powerful and essential tool for searching text within files on Linux systems. By understanding its basic syntax and commonly used options, you can quickly locate specific information, troubleshoot issues, and analyze logs more efficiently. Whether you are a beginner or an experienced Linux user, mastering grep will significantly improve your productivity and command-line skills.
