Use Grep And Regular Expressions To Analyze Text
General Information
Pattern matching with grep.
Filter lines that start with (^) a comment (#) in myfile.txt
grep "^#" myfile.txt
Filter for “auth”, ignore case
grep -i "auth" /etc/ssh/ssh_config
Common Grep Options
- -i ⇒ ignore case
- -v ⇒ invert match (show non-matching lines)
- -c ⇒ output the count of matches (or count of non-matching if used with -v)
- -o ⇒ print only the matched parts of the matching line
- -n ⇒ prefix each line of output with the line number
Regular Expression Matching
- ^ ⇒ starts with
- $ ⇒ ends with
- [ab] ⇒ match a or b
- [^ab] ⇒ do not match a or b
- ? ⇒ previous item optional (match 0 or 1 time)
- * ⇒ previous item matched zero or more times
- + ⇒ previous item matched one or more times
- . ⇒ match any single character (the period)
- {x} ⇒ previous item matched exactly x times
- {x,} ⇒ previous item matched x or more times
- {,y} ⇒ previous item matched at max y times
- {x,y} ⇒ previous item matched at least x times, but not more than y times