In Linux, grep is a very common and important tool. It is a command that every professional operation and maintenance engineer must master, because it can quickly find and filter files in files. Content, so how to use grep in Linux system? The following is an introduction to common usage, let’s take a look.
1. Basic usage
The grep command is mainly used to search for lines of a specified pattern in files. For example, to find the line containing "example" in the file file.txt, you can use the grep command.
grep ‘example’file.txt
Grep will output all lines containing 'example'.
2. Ignore case
grep is case-sensitive by default, but you can use the -i option to search regardless of case. For example, execute the following command to find lines containing 'example' in the file, regardless of case.
grep -i “example” file.txt
3. Regular expression search
grep supports using regular expressions for *level searches. For example, to find lines starting with "example", you can use the regular expression anchor symbol "^":
grep “^example” file.txt
This will output all lines starting with "example".
4. Reverse search:
Sometimes it is necessary to find lines that do not contain the specified pattern. You can use the -v option to perform a reverse search. For example, to find lines that do not contain "example", you can execute the following command:
grep -v “example”file.txt
Grep will output all lines that do not contain "example".
5. Count the number of matching lines
If you only care about the number of matching lines, you can use the -c option to count the number of matching lines. For example, to count the number of lines containing "example" in the file, you can execute the following command:
grep -c “example”file.txt
Grep will output the number of matching lines.
6. Recursive search
If you want to recursively search for files in a directory and its subdirectories, you can use the -r option. For example, to find lines containing "example" in the current directory and its subdirectories, you can execute the following command:
grep -r “example”.
Grep will search all files recursively and output the lines containing "example".
The above is the detailed content of How to use grep in Linux system?. For more information, please follow other related articles on the PHP Chinese website!