工作必备之正则匹配、grep、sed、awk

常用正则:
匹配空行:^\s*\n

匹配www开头:^www

 1.所有域名前加www.
sed -e "/^$/d" -e 's/^/www./g' file

2.分组调换
echo aaa BBB | sed 's/\([a-z]\+\) \([A-Z]\+\)/\2 \1/'

BBB   aaa

3.awk的格式化输出
awk -F: 'BEGIN{printf "%-10s\t %s\n","用户名称","用户ID"} {printf "%-10s\t %s\n",$1,$3}' /etc/passwd


4.当使用 {x,y} 这种次数匹配的正则表达式时,需要配合--posix选项或者--re-interval选项。
awk '/he{2,3}llo/{print $0}' test.txt        ====>错误

awk --posix  '/he{2,3}llo/{print $0}' test.txt
或者
awk --re-interval  '/he{2,3}llo/{print $0}' test.txt

5.匹配test.txt中第一次出现Lee至第一次出现Kevin范围内的打印出来
awk '/Lee/,/Kevin/{print $0}' test.txt

6.打印第三行至第7行的内容
awk 'NR>=3 && NR<=6' {print $0} test.txt

7.利用awk对空数组赋值为0的特性,统计出ip.txt里面每个IP出现的次数
ip.txt的内容如下:
192.168.1.1
192.168.1.2
192.168.1.1
192.168.1.100
192.168.1.2

awk '{ count[$1]++ } END{for (i in count){print i,count[i]} }'  ip.txt



最终打印的结果为:
192.168.1.1    2
192.168.1.2    2
192.168.1.100    1

猜你喜欢

转载自www.cnblogs.com/steven9898/p/11324322.html