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
相关文章
相关标签/搜索