1. 程式人生 > 其它 >linux基礎之grep訓練

linux基礎之grep訓練

grep [OPTIONS] PATTERN [FILE...] 
    選項:
        --color=auto: 對匹配到的文字著色顯示
        -v : 顯示不能夠被pattern匹配到的行
        -i : 忽略字元大小寫
        -o : 僅顯示匹配到的單詞
        -q: 靜默模式,不輸出任何訊息
        -A # :after, 後#行
        -B # :before,前#行
        -C # : context, 前後各#行
        -E ; 使用擴充套件的正則表示式
 
     grep練習:
    
1. 顯示/proc/meminfo 檔案中以大小寫s開頭的行:(要求: 使用兩種方式) # grep "^[sS]" /proc/meninfo # grep -i "^s" /proc/meminfo 2. 顯示/etc/passwd檔案中不以/bin/bash結尾的行 # grep -v "/bin/bash$" /etc/passwd 3. 顯示/etc/passwd 檔案中ID號最大的使用者的使用者名稱 # sort -t: -k 3 -n /etc/passwd | tail -1 | cut -d: -f1 4.如果使用者root存在,顯示其預設的shell程式 #
grep "^root\>" /etc/passwd &> /dev/null | cut -d: -f7 # id root &> /dev/null && grep "^root\>" /etc/passwd | cut -d: -f7 5. 找出/etc/passwd中的兩位或三位數 # grep -o "\<[0-9]\{2,3\}\>" /etc/passwd 6.顯示/etc/rc.d/rc.sysinit檔案中,至少以一個空白字元開頭的且後面存在非空白字元的行 # grep
"^[[:space:]].*[^[:space:]].*" # grep "^\([[:space:]]\).*[^\1].*" # grep "^[[:space:]]"\+[^[:space:]] 7.找出netstat -tan 命令的結果中以 LISTEN 後跟0、1或多個空白字元結尾的行 # netstat -tan | grep "LISTEN[[:SPACE:]]*$" 8.新增使用者bash、testbash、basher以及nologin(其shell為/sbin/nologin):而後找出/etc/passwd檔案中使用者名稱同shell名的行 # useradd -s /sbin/nologin nologin # useradd bash # grep "^\([[:alnum:]]\+\>\).*\1$" /etc/passwd 9. 寫一個指令碼,實現如下功能 如果user1使用者存在,就顯示其存在,否則新增之 顯示新增的使用者的id號等資訊 #!/bin/bash id user1 &> /dev/null && echo "user1已存在" || useradd user1 id user1 10. 寫一個指令碼,完成如下功能 如果root使用者登入了當前系統,就顯示root使用者線上,否則說明其未登入 #!/bin/bash w | grep "^root\>" &> /dev/null && echo "root logged" || echo "root not logged" egrep = grep -E egrep [OPTIONS] PATTERN [FILE...] egrep練習: 1.顯示當前系統root、centos或user1使用者的預設shell和UID # egrep "^root|centos|user1\>" /etc/passwd | cut -d: -f3,7 2.找出/etc/rc.d/init.d/functions檔案(centos6)中某單詞後面跟一個小括號的行 # egrep -o "^[_[:alnum:]]+\(\)" /etc/rc.d/init.d/functions 3.使用echo輸出一絕對路徑,使用egrep取出其基名 # echo "/etc/rc.d/init.d/functions" | egrep -o "[^\/]+" | tail -1 進一步:使用egrep取出路徑的目錄名,類似於dirname命令的結果 # echo "/tmp/init.d/function/base.txt" | egrep "(\/).*\1\b" 4.找出ifconfig命令結果中1-255之間的數值 # ifconfig | egrep "\<([1-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\>"