grep sed awk

一、grep ,用來過濾,也能夠用來過濾日記,某個關鍵字等;bash

選項:編輯器

..net

*code

.*  0或多排序

?  0或1文檔

+  1或多字符串

^get

$io

^$class

|                    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
相關文章
相關標籤/搜索