Skip to main content

grep

教學網站

文字過濾

使用 . (period) 表示一個任意字元
$ grep dev.sda /etc/fstab
/dev/sda3       /               reiserfs        noatime,ro 1 1
/dev/sda1       /boot           reiserfs        noauto,noatime,notail 1 2
/dev/sda2       swap            swap            sw 0 0
#/dev/sda4      /mnt/extra      reiserfs        noatime,rw 1 1

使用 [ ]
$ grep dev.sda[12] /etc/fstab
/dev/sda1       /boot           reiserfs        noauto,noatime,notail 1 2
/dev/sda2       swap            swap            sw 0 0 

使用 [^12] 表示非1,2字元
$ grep dev.sda[^12] /etc/fstab
/dev/sda3       /               reiserfs        noatime,ro 1 1
#/dev/sda4      /mnt/extra      reiserfs        noatime,rw 1 1

使用正規表示
$ grep '^#' /etc/fstab
# /etc/fstab: static file system information.
#
$ grep '^#.*\.$' /etc/fstab
# /etc/fstab: static file system information.
#
$ grep 'foo$' filename

搜尋與關鍵字大小寫一致的行
grep -w "boo" myfile.txt
grep "\<boo\>" myfile.txt

搜尋包含特殊字元 *** 的關鍵字
grep '\*\*\*' myfile.txt

搜尋 email 地址
grep -E -o "\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,6}\b" /path/to/data

搜尋 IP 位址
egrep '\b(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?\.){3}(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)' /etc/hosts
grep -E -o "(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)" /var/log/auth.log

更多應用語法
grep '[vV][iI][Vv][Ee][kK]' filename
grep '[vV]ivek' filename
grep -w '[vV]ivek[0-9]' filename
grep 'foo[0-9][0-9]' filename
grep '[A-Za-z]' filename
grep [wn] filename

搜尋多個關鍵字(使用正規運算式)

ls /var/log/ | grep -E "http|secure"

ls /var/log/ | grep "http\|secure" 

grep -Ev "^(#|;)" example.txt

檢查設定檔的參數

 CONFIG_CHECK=`grep "^# SparkleShare$" /etc/ssh/sshd_config`
  if ! [ "$CONFIG_CHECK" = "# SparkleShare" ]; then
    echo "" >> /etc/ssh/sshd_config
    echo "# SparkleShare" >> /etc/ssh/sshd_config
    echo "Match User storage" >> /etc/ssh/sshd_config
    echo "    PasswordAuthentication no" >> /etc/ssh/sshd_config
  fi

在許多檔案內尋找特定字串內容
應用:程式碼編寫及除錯

cd /var/www/html
grep -r "[搜尋關鍵字]" *

grep -Ril "specific_text" /path/to/dir 

搜尋特定字串的文字段落內容
應用:檢查系統的硬體裝置,以及類似 AIX 的 grep -p

見附檔: grepp.awk