1. 程式人生 > >grep sed awk

grep sed awk

1、grep ,用來過濾,也可以用來過濾日記,某個關鍵字等;

選項:

.

*

.*  0或多

?  0或1

+  1或多

^

$

^$

|                    egrep '^root|bash' /etc/passwd             egrep  ^(root|test)   /ec/passwd

word{n}          grep  '[oo]\{3\}'  /etc/passwd  ===   egrep   '[oo]{3}'  /etc/passwd    #當多個字元(多個o),則需要用方括號;

word{1,3}       grep  '[oo]\{1,3\}'  /etc/passwd   ==   egrep  '[oo]{1,3}'   /etc/passwd

[ ]          [0-9a-zA-Z]                      {1,3,4}

選項:  -c(count-line)        -n(number-line)              -v    -i    -r/R               -A(下)       -B        -C

^word

[^word]      過濾出非什麼的行;只要是內容包括即可;

[^word]               過濾出非什麼開頭的行;

[^0-9]           [^a-zA-Z]              [^0-9a-zA-Z]       

egrep               表示在使用egrep時,可以使用   +   ?     |     {}

grep  -r  --include    "*.txt"   'root'       /home/        #過濾出/home/目錄下的txt文字中包含root的行;

sed:支援查詢和替換,不過更重要的是替換;

語法:sed    options    commond   file

options:

-n    

-p 

-d

-i  

-e

-r        脫義 

I

三種替換方法:      s@@@g   ===      s###g    ====    s///g

也支援列印指定行:   sed   -n  '1'p  /etc/passwd       sed   -n   '1,4'p   /etc/passwd

也支援多個選項: -e     sed   -ne   '1'p    -e   '/bus/'p    /etc/passwd

替換:  sed   '1,10s#root#toor#g'   /etc/passwd

也可以用替換來刪除內容:  sed  's#[a-zA-Z0-9]##g'  1.txt

[root@localhost_002 ~]# sed 's#[a-zA-Z0-9]##g' 1.txt

可以在所有的字母前加;

head  -10 1.txt|sed 's#^#aaa:#g'

head  -10 1.txt|sed -r 's#(.*)#aaa:\1#g'

head -10 1.txt|sed -r  's#[a-z]#\U&#g'        內容全部小寫變大寫

head -10 1.txt|sed -r  's#[A-Z]#\U&#g'         大變小

head -10 1.txt|sed -r  's#\b[a-z]#\U&#g'   首字大寫

awk:流式編輯器,相容sed的所有功能;

awk  '{print $n}'  filename          當n等0,代表整個文件,當等於數字時,則代表第數字行;

awk預設是以空格  空白字元   tab     為分隔符;

 awk -F ':' '{print $1,$3,$5}' /etc/passwd

也可以手動指定分隔符:    awk  -F ':' '{print $1"#"$3"#"$5}'  /etc/passwd

awk的匹配:    awk   '/oo/'   1.txt

awk    '$1~/root'  1.txt

awk  -F ':'  '/root|bash/ {print $0}'  1.txt

awk還支援數值的表示式; ==    >=    <=   !=   ==

awk  -F ':'   '$3>=1000 {print $1}'  1.txt

awk  -F ':'   '$3>="1000" {print $1}'  1.txt

註釋:加上雙引號被當做字串,以ASCII二進位制排序處理,      不加雙引號則是數值處理;

awk -F ':' '$1=="root" {print $0}' test.txt              $0則表示整行;

awk  -F ':'  '$3==$4'   /etc/passwd

awk   -F ':'   $71="/sbin/nologin"   /etc/passwd

awk  -F  ':'   '$3>5 && $5<7  '{print $0}'   /etc/passwd

&&   表示並且的意思                             | |        表示或者的意思

awk -F ':'  '{OFS="#"}  {print $1,$3,$5}'   /etc/passwd

NR 表示行號 (number row)               $NR 表示行,一般指第一行;

[root@localhost_002 ~]# awk -F ':' '{print $NR}' /etc/passwd
root
x
2
4
lp
/sbin
/sbin/shutdown

 NF  表示列號,          $NF  表示文件的最後一列(右側一列)

awk   -F  ':'   '{(tot=tot+$3)};END {print $tot}'  /etc/passwd

[root@localhost_002 ~]# awk -F ':' '{(t=t+$3)};END {print t}' /etc/passwd
6676