How to search for a string in a file using the grep command?

Published on Aug. 22, 2023, 12:17 p.m.

To search for a string in a file using the grep command, you can use the following syntax:

grep pattern file_name

Here pattern represents the string you want to search for, and file_name is the name of the file you want to search through. For example, to search for the word “example” in the file test.txt, you would run:

grep example test.txt

This will search through the contents of test.txt and display any lines that contain the word “example”. By default, grep is case sensitive, but you can use the -i option to make the search case insensitive. For example:

grep -i example test.txt

This will search for the word “example” in test.txt regardless of whether it appears in uppercase or lowercase.

grep also supports searching through multiple files at once by using wildcard characters to specify the file(s) to search. For example, to search for the word “example” in all files with the .txt extension in the current directory, you would run:

grep example *.txt

This will search through all files in the current directory with the .txt extension and display any lines that contain the word “example”.

Note that grep is a powerful tool that can be used for more complex search patterns, such as regular expressions. For more information on using grep, you can refer to the man pages by running man grep in a terminal.

Tags: