Jex’s Note

Grep 指令

一般用法

grep -R '時間' *
  • -r, –recursive like –directories=recurse
  • -R, –dereference-recursive likewise, but follow all symlinks
  • –include=FILE_PATTERN search only files that match FILE_PATTERN
  • –exclude=FILE_PATTERN skip files and directories matching FILE_PATTERN
  • –exclude-from=FILE skip files matching any file pattern from FILE
  • –exclude-dir=PATTERN directories that match PATTERN will be skipped.
  • -i, –ignore-case ignore case distinctions
  • -P, –perl-regexp
  • -o, –only-matching

grep ^d:過濾出資料夾

OR

沒有任何 option, 必須使用 \| 來分隔 pattern :

grep 'pattern1\|pattern2' filename
grep 'Tech\|Sales' employee.txt

使用 option -E (extended regexp), 使用 | 分隔 pattern :

grep -E 'pattern1|pattern2' filename
grep -E 'Tech|Sales' employee.txt

使用 egrep 指令, 相當於使用 grep -E :

egrep 'pattern1|pattern2' filename
egrep 'Tech|Sales' employee.txt

使用 option -e, 但 pattern 必須分開寫

grep -e pattern1 -e pattern2 filename
grep -e Tech -e Sales employee.txt

AND

AND 在 grep 沒有操作符, 可以使用 -E 達成 :

grep -E 'pattern1.*pattern2' filename
grep -E 'pattern1.*pattern2|pattern2.*pattern1' filename
grep -E 'Dev.*Tech' employee.txt
grep -E 'Manager.*Sales|Sales.*Manager' employee.txt

使用 linux 原生指令 | 來達成 :

grep -E 'pattern1' filename | grep -E 'pattern2'
grep Manager employee.txt | grep Sales

NOT

使用 -v (invert match) 達成, 它會顯示除了符合 pattern 以外的搜尋結果

grep -v 'pattern1' filename
grep -v Sales employee.txt
egrep 'Manager|Developer' employee.txt | grep -v Sales

Others

只過濾出符合的部份

echo 'hello world' | grep -oP 'hello \K(world)'

ref : http://www.thegeekstuff.com/2011/10/grep-or-and-not-operators/

Comments