grep

grep

  • grep 這個指令名稱其實是來自於正規表示法的 g/RE/p,其意義是代表以正規表示法全域搜尋並列印出來(globally search for RE and print it)

基本使用

1
2
3
4
5
// temp.txt
It is a great day, and IS sunny day
he want to say hello world for each one
there are many works to do
let's keep moving forward
  • 用法

    1
    grep key_word file1 file2 ...
  • e.g.

    1
    2
    3
    4
    5
    6
    $ grep "hello world" ~/temp.txt
    i want to say hello world for each one

    $ grep "hello world" ~/*.txt
    *
    /Users/linyunwen/temp.txt:i want to say hello world for each one

    參數引用

  • options

    • -a : 把binary 檔案用 text 檔案的方式搜尋資料
    • -c : 計算找到 ‘搜尋字串’ 的次數(count)
      1
      2
      grep "he" ~/temp.txt -c
      2
    • -i : 忽略大小寫的不同 (case-insensitive search)
      1
      2
      3
      4
      $ grep "is" ~/temp.txt -i
      It is a great day, and IS sunny day
      $ grep "is" ~/temp.txt
      It is a great day, and IS sunny day
    • -n : 輸出行號,在每行的前面加上行號
      1
      2
      $ grep "hello world" ~/temp.txt -n
      2:he want to say **hello world** for each one
    • -v : 反向搜索,意指去除匹配到的結果 (–invert-match)
      1
      2
      3
      4
      $ grep -v "hello world" ~/temp.txt
      It is a great day, and IS sunny day
      there are many works to do
      let's keep moving forward
    • -V : 大寫的V,顯示出來grep的版本 (version)
      1
      2
      $ grep -V
      grep (BSD grep) 2.5.1-FreeBSD
    • -r : recursive search
      1
      2
      3
      4
      $ grep -r "hello word" ~/Downloads/

      // 可以使用 -r 搭配 --include 指定檔案類型:
      $ grep -r --include=".html" "hello word" ~/Downloads/
    • -A [n] : 多顯示後 n 行 (after)
      1
      2
      3
      4
      $ grep -A 2 "hello world" ~/temp.txt
      he want to say hello world for each one
      there are many works to do
      let's keep moving forward
    • -B [n] : 多顯示前 n 行 (before)
      1
      2
      3
      $ grep -B 1 "hello world" ~/temp.txt
      It is a great day, and IS sunny day
      he want to say hello world for each one
    • -C [n] : 多顯示前後各 n 行 (content)
      1
      2
      3
      4
      $ grep -C 1 "hello world" ~/temp.txt
      It is a great day, and IS sunny day
      he want to say hello world for each one
      there are many works to do
    • -w : whole word
      1
      2
      3
      4
      5
      $ grep  "he" ~/temp.txt
      he want to say hello world for each one
      there are many works to do
      $ grep -w "he" ~/temp.txt
      he want to say hello world for each one
  • 亦可搭配 pipe 處理資料流

    • e.g.
      1
      2
      # 篩選含有 network 關鍵字的檔案名稱
      ls /etc/ | grep network
  • 顏色標示

    • grep 可以使用顏色標示的方式,將成功匹配的部分文字標示出來,方便使用者閱讀
    • 顏色標示功能可以透過
      • --color=never--color=always--color=auto
        1
        export GREP\_OPTIONS='--color=auto' GREP\_COLOR='100;8'

reference