Grep Command In Linux Example
Chapter:
Linux Commands
Last Updated:
10-05-2023 02:17:36 UTC
Program:
/* ............... START ............... */
/*
Searching for a pattern within a file:
Let's say we have a file named example.txt that contains the following lines:
This is line 1.
This is line 2.
This is line 3.
*/
To search for the pattern "line" within this file, you can use the grep command as follows:
grep "line" example.txt
Output will be as follows
This is line 1.
This is line 2.
This is line 3.
/*
Searching for a pattern in multiple files:
If you have multiple files in the same directory and you want to search for a pattern in all of them,
you can use a wildcard character (*) to specify the files. For example, if you have files
named file1.txt, file2.txt, and file3.txt, and you want to search for the pattern "example"
in all of them, you can use the following command:
*/
grep "example" file*.txt
Output will be as follows , The output shows the matching lines along with the corresponding filenames.
file1.txt: This is an example.
file2.txt: Another example here.
file3.txt: Yet another example.
/*
Searching recursively in a directory:
If you want to search for a pattern in all files within a directory and its subdirectories,
you can use the -r (or --recursive) option with grep. For example, if you want to search for
the pattern "error" within all files in the current directory and its subdirectories, you can use the following command:
*/
grep -r "error"
Output will be as follows
./file1.txt: This is an error message.
./subdirectory/file2.txt: Another error occurred.
/* ............... END ............... */
Notes:
-
The grep command in Linux is used for searching text patterns within files or input streams. Here's an example of how you can use the grep command:
- Above commands are just a few examples of how you can use the grep command in Linux. The command provides various options and advanced features for pattern matching and text manipulation. You can refer to the grep man page (man grep) for more information and to explore additional options.