[LINUX] How to use the grep command and frequent samples
grep command
A command to search for matching lines in a regular expression
syntax
grep [option] pattern [file]
ex: grep -n abc aaa.txt
importance
★★★★★(5/5)
Required. If you don't remember this, it will hinder your daily work.
Options
Options you want to remember
- -e: Use regular expressions (regex e?)
- -n: Show line number in search results (number, common abbreviation)
- -C5: Display the specified 5 lines before and after the part that matches the search result (the number of lines is arbitrary. Maybe C has no meaning, before, after, and before and after each match in A, B, C, so ABC which Maybe you should remember it
- -r: Search in directories (recursive, common omission)
- -i: Case insensitive search (case insensitive i. Maybe ...)
Options you want to remember if you can
- -v: Do not match
- -B3: Display the previous 3 matching lines (the number is arbitrary)
- -A2: Display 2 lines after matching (number is arbitrary)
Options that you don't have to remember (for each person)
- -E: Search by extended regular expression
- -l: Show only file name in search results
- -h: Do not show file name in search results
- -o: Display characters that match the search results
- -L: Show not applicable files
sample
- grep'^ A'sample.csv → A is added at the beginning of the line
- grep'\ [0-9]' sample.csv → Extract the line containing the character string'[0-9]'
- ps aux | grep python → Extract processes that contain the characters python
- grep -v'^ A'sample.csv → A is not added at the beginning of the line
- grep -e aaa -e bbb sample.csv → Extract the line containing either aaa or bbb
- grep -i aaa sample.csv → Case-insensitive, extract lines containing aaa
appendix
If you want to perform an AND search with grep
grep aaa sample.csv | grep bbb
→ Narrow down to those that contain aaa, and further narrow down to those that contain bbb
If you want to do an OR search with grep
grep -e aaa-e bbb sample.csv
→ Repeat the -e option multiple times. Extract the line containing aaa and the line containing bbb.
I want to extract the one with a specific file name
ls ./ | grep aaa
→ Extract files containing aaa (file name) in the current directory (current directory).
I want to extract a file that contains specific content
grep aaa -rl ./
→ Files in the current directory (current directory) that contain aaa
I want to find out the latest command containing a specific character string from the history of executed commands.
history | grep aaa | tail
→ Extract commands including aaa from history commands. Narrow down to the last 5 with tail.
Summary
The grep command is required, so it's a good idea to remember it!