grep 經常使用實例

part01php

一、找出/proc/meminfo文件中,全部以大寫或小寫s開頭的行,至少三種實現方式  html

grep '^[Ss]' /proc/meminfo
grep -i '^s' /proc/meminfo
grep -E '^(S|s)' /proc/meminfo

二、顯示當前系統上root、centos、或者user1用戶的相關信息git

   

grep -E "^(root\>|centos\>|user1\>)" /etc/passwd

三、找出/etc/rc.d/init.d/functions文件中某單詞後面跟一個小括號的行shell

grep -E "[_[:alnum:]]+?\(\)" /etc/rc.d/init.d/functions

四、使用echo命令輸出一絕對路徑,使用grep取出其基名centos

echo /etc/sysconfig/network-scripts/ifcfg-eth0 | grep -Eo "(\<[^/]+?)$"

進一步:取出其路徑名,相似於對其執行dirname命令的結果   bash

 echo /etc/sysconfig/network-scripts/ifcfg-eth0 | grep -Eo "^/(.*)/"

五、找出ifconfig命令結果中的1-255之間的數值ide

ifconfig | grep -E "\<[1-9]\>|\<[0-9][1-9]\>|\<1[0-9][0-9]\>|\<2[0-5][0-5]\>"

六、添加用戶bash,testbash,basher以及nologin(其shell爲/sbin/nolgin);然後找出/etc/passwd文件用戶名同shell名的行ui

grep -E "^(\<.*\>).*(\1)$" /etc/passwd
grep -E "^[^:]+\>" /etc/passwd
grep -Eo "^([^:]+\>).*\1$" /etc/passwd

七、獲取ifconfig命令中的IP地址,使用三種方式實現spa

ifconfig  | grep -o '\([0-9]\{1,3\}\.\)\{3\}[0-9]\{1,3\}'
ifconfig | grep -o '\b[0-9]\{1,3\}\b\.\b[0-9]\{1,3\}\b\.\b[0-9]\{1,3\}\b\.\b[0-9]\{1,3\}\b'
ifconfig  | grep -Po '(?<=inet)(.*)(?=net)'


part02日誌

一、只在目錄中全部的.php和.html文件中遞歸搜索字符」main()」

grep "main()" . -r --include *.{php,html}

二、在搜索結果中排除全部README文件

grep "main()" . -r --exclude "README"

三、在搜索結果中排除filelist文件列表裏的文件

grep "main()" . -r --exclude-from filelist

四、在多級目錄中對文本進行遞歸搜索

grep "string" . -r -n

五、搜索多個文件並查找匹配文本在哪些文件中

grep -1 "root" /etc/fstab  /etc/passwd

六、搜索開頭不是英文字母的行,並顯示行號

grep -n '^[^a-zA-Z]' /etc/fstab

七、搜索c後面跟1,2個d,後面再跟一個3的字符串的行

grep 'UUID=cd\{1,2\}3' /etc/fstab

八、過濾空行和開始爲#開始的行

grep -Ev '^#|^$' /etc/fstab

九、 找出/etc/rc.d/rc.sysinit或/etc/grub2.cfg g文件中,以致少一個空白字符開頭,且後面存在非空白字符的行

grep "^[[:space:]]\+[^[:space:]]" /etc/grub2.cfg

十、列出系統全部系統用戶(Centos 7)

grep "\<\([[:digit:]]\)\{2,3\}\>" /etc/passwd

十一、過濾functions文件中,以單詞或者單詞前面跟了一個」_「開頭的行,並顯示先後2行

grep -E2 "^[_[:alnum:]]+\\(\\)" /etc/rc.d/init.d/functions


part03

一、顯示/etc/rc.d/rc.sysinit中以#開頭,且後面跟一個或多個空白字符,然後又跟了任意非空白字符的行

grep "^#[[:space:]]\+.\+" /etc/rc.d/rc.sysinit

二、查找/proc/cpuinfo文件中關鍵字,並顯示先後1行

grep -C 1 "GenuineIntel" /proc/cpuinfo

三、查找包含至少一個 root關鍵字 的文件

find . -type f -print0| xargs -0 grep -c banana| grep -v ":0$"

四、查找文本中的全部QQ郵箱

grep -E "^[1-9]{1}[0-9]{1,10}@qq.com$" mail_list.txt

五、查找default和dev兩個關鍵字

grep -e "defaulkt" -e "dev" /etc/fstab

六、查找/etc目錄下,全部包含root關鍵字的文件並顯示文件路徑及文件名

grep -lr "root" /etc/ | xargs ls -l

七、監控日誌文檔中產生Error的行,並只打印包含Error的行

tailf /var/www/logs/error.log  | grep --line-buffered "Error"
相關文章
相關標籤/搜索