grep常见操作整理(更新)

时间:2023-03-09 01:54:01
grep常见操作整理(更新)

提取邮箱和URL

[root@test88 ~]# cat url_email.txt
root@gmail.com,http://blog.peter.com,peter@qq.com [root@test88 ~]# egrep -o '[A-Za-z0-9._]+@[A-Za-z0-9.]+\.[A-Za-z]{2,4}' url_email.txt
root@gmail.com
peter@qq.com [root@test88 ~]# egrep -o "http://[A-Za-z0-9.]+\.[A-Za-z]{2,4}" url_email.txt
http://blog.peter.com

常用选项整理

grep -v 排除内容
grep -B 显示匹配行和之前num行
grep -A 显示匹配行和之后num行
grep -C 显示匹配行和前后num行
grep --color=auto 匹配字符串加色显示
grep -n 打印行号
grep -i 不区分大小写
grep -w 匹配单词
grep -E 即egrep使用扩展正则表达式
grep -e 匹配多个模式
grep -c 匹配到的行数 [root@test88 ~]# cat test.txt
one
two
three
four
five
ONE
TWO
THREE
FOUR
FIVE #grep -v 取反
[root@test88 ~]# grep -v t test.txt
one
four
five #grep -n 行号
[root@test88 ~]# grep -n t test.txt
2:two
3:three #grep -c 行数
[root@test88 ~]# grep -c t test.txt
2 #grep -i 不区分大小写
[root@test88 ~]# grep -i t test.txt
two
three
TWO
THREE #grep -e 匹配多个模式
[root@test88 ~]# grep -e t -e f test.txt
two
three
four
five #grep -B 匹配行和前面n行
[root@test88 ~]# grep -n four -B 3 test.txt
1-one
2-two
3-three
4:four #grep -A 匹配行和后面n行
[root@test88 ~]# grep -n one -A 3 test.txt
1:one
2-two
3-three
4-four #grep -C 匹配行和前后n行
[root@test88 ~]# grep -n two -C 1 test.txt
1-one
2:two
3-three #grep -w 匹配单词
[root@test88 ~]# grep -w two test.txt
two #grep -E 使用扩展正则表达式,等同egrep
[root@test88 ~]# grep -E "t|f" test.txt
two
three
four
five