Reprint Link: http://www.eguidedog.net/linux-tutorial/05-grep.php
grep is a command that is commonly used under the Linux command line to find the contents of a filtered text file. The simplest usage is:
grep Apple Fruitlist.txt
If you want to ignore case, you can use the-I parameter:
grep-i Apple Fruitlist.txt
If you want to search all the files in the directory, including subdirectories, and display line numbers in the results, you can use the following command:
GREP-NR Apple *
GREP's syntax supports regular expressions, and regular expressions are a bit more complex to explain later. Here are some useful parameters:
- -A num,--after-context=num: num rows After matching rows are output at the same time in the results
- -B num,--before-context=num: The num rows before matching rows are output in the results, and sometimes we need to display a few lines of context.
- -I,--ignore-case: Ignore case
- -N,--line-number: Displays line numbers
- -R,-R,--recursive: Recursive search subdirectories
- -V,--invert-match: output no matching rows
We can make grep more powerful by pipeline operation, which is to use the output of the previous command as input to the following command, which combines many simple commands to accomplish complex functions. For example, if we want to find a line that contains Apple, but want to filter out pineapple, you can use the following command:
grep Apple fruitlist.txt | grep-v Pineapple
If we want to save the search results, we can redirect the command's standard output to the file:
grep Apple Fruitlist.txt | grep-v pineapple > Apples.txt
REDIRECT Symbol > and pipe operation symbol | The difference is that a redirect is followed by a file that cannot be followed by any files or commands, and the pipe operation is followed by a command that can be infinitely connected. If you want to write to the file in Append mode, you can use >>. Pipeline operation is a philosophy of the Linux command line, which is one of the few technologies in computer technology that can be used for decades. With pipeline operation, a line of commands can complete the text processing functions that are not completed by thousands of lines under Windows.
Linux Find file contents (grep)