Skip to content

Latest commit

 

History

History
89 lines (80 loc) · 2.45 KB

5.41-正则三剑客.md

File metadata and controls

89 lines (80 loc) · 2.45 KB

什么是正则

正则就是一串有规律的字符串
掌握好正则对于编写shell脚本有很大帮助
各种编程语言中都有正则,原理是一样的
本章将要学习grep/egrep、sed、awk

grep

 grep [-cinvABC] 'word' filename 
 -c 行数
 -i 不区分大小写
 -n 显示行号
 -v 取反
 -r 遍历所有子目录
 -A 后面跟数字,过滤出符合要求的行以及下面n行
 -B 同上,过滤出符合要求的行以及上面n行
 -C 同上,同时过滤出符合要求的行以及上下各n行
 grep -n 'root' /etc/passwd
 grep -nv 'nologin' /etc/passwd
 grep '[0-9]'/etc/inittab
 grep -v '[0-9]'/etc/inittab
 grep -v '^#' /etc/inittab
 grep -v '^#' /etc/inittab|grep -v  '^$'
 grep '^[^a-zA-Z]' test.txt
 grep 'r.o' test.txt
 grep 'oo*' test.txt
 grep '.*' test.txt
 grep 'o\{2\}' /etc/passwd
 egrep 'o{2}' /etc/passwd
 egrep 'o+' /etc/passwd
 egrep 'oo?' /etc/passwd
 egrep 'root|nologin' /etc/passwd
 egrep '(oo){2}' /etc/passwd

sed

 sed -n '5'p test.txt 
 sed -n '1,5'p test.txt
 sed -n '1,$'p test.txt
 sed -n '/root/'p test.txt
 sed -n '/^1/'p test.txt
 sed -n 'in$'p test.txt
 sed -n '/r..o/'p test.txt
 sed -n 'oo*'p test.txt
 sed -e '1'p -e '/111/'p -n test.txt
 sed '1'd test.txt
 sed '1,3'd test.txt
 sed '/oot/'d test.txt
 sed '1,2s/ot/to/g' test.txt
 sed 's#ot#to#g' test.txt
 sed 's/[0-9]//g' test.txt
 sed 's/[a-zA-Z]//g' test.txt
 sed -r 's/(rot)(.*)(bash)/\3\2\1/' test.txt
 sed 's/^.*$/123&/' test.txt
 sed -i 's/ot/to/g' test.txt

awk

 head -n2 test.txt|awk -F ':' '{print $1}'
 head -n2 test.txt|awk -F ':' '{print $0}'
 awk -F ':' '{print $1"#"$2"#"$3"#"$4}'
 awk '/oo/' test.txt
 awk -F ':' '$1 ~/oo/' test.txt
 awk -F ':' '/root/ {print $1,$3} /test/ {print $1,$3}' test.txt
 awk -F ':' '$3=="0"' /etc/passwd
 awk -F ':' '$3>="500"' /etc/passwd
 awk -F ':' '$3>=500' /etc/passwd 
 awk -F ':' '$7!="/sbin/nologin"' /etc/passwd
 awk -F ':' '$3<$4' /etc/passwd
 awk -F ':' '$3>"5" && $3<"7"' /etc/passwd
 awk -F ':' '$3>1000 || $7=="/bin/bash"' /etc/passwd
 head -5 /etc/passwd |awk -F ':' '{OFS="#"} {print $1,$3,$4}‘
 awk -F ':' '{OFS="#"} {if ($3>1000) {print $1,$2,$3,$4}}' /etc/passwd
 head -n3 /etc/passwd | awk -F ':' '{print NF}‘
 head -n3 /etc/passwd | awk -F ':' '{print NR}‘
 awk 'NR>40' /etc/passwd
 awk -F ':' 'NR<20 && $1 ~ /roo/' /etc/passwd
 head -n 3 /etc/passwd |awk -F ':' '$1="root"‘
 awk -F ':' '{(tot=tot+$3)}; END {print tot}' /etc/passwd
 awk -F ':' '{if ($1=="root") {print $0}}' /etc/passwd