1. 程式人生 > >[CentOS 7系列]grep/egrep

[CentOS 7系列]grep/egrep

grep、egrep

在開發腳本的時候,我們總會發現需要調用的某些字符串時有規律的。通過篩選、提取和調用這些有規律的字符串,完善腳本的處理流程。正則就是這麽一串有規律的字符串。在各種編程語言中都有正則,原理基本一致。在linux學習中,掌握好正則對於編寫shell腳本能打下深厚根基。

grep/egrep是shell腳本中常用的篩選命令之一。通過該命令配合正則表達式能夠有效快速的篩選出需要的文本內容。


▎grep命令的基本用法:grep [-cinvrABC] ‘word‘ filename

參 數作 用
-c統計匹配的行數
-i不區分大小寫
-n顯示行號
-v取反
-r遍歷所有子目錄
-A後面跟數字,過濾出符合要求的行以及下面的n行
-B後面跟數字,過濾出符合要求的行以及上面的n行
-C後面跟數字,過濾出符合要求的行以及上下各n行

測試示例:

[[email protected] test1]# grep -c sbin 1.txt
11
[[email protected] test1]# grep -i root 1.txt
root:x:0:0:root:/Root:/bin/bash
operator:x:11:0:operator:/Root:/sbin/nologin
[[email protected] test1]# grep -ni root 1.txt
1:root:x:0:0:root:/Root:/bin/bash
10:operator:x:11:0:operator:/Root:/sbin/nologin
[[email protected]
/* */ test1]# grep -niv root 1.txt 2:bin:x:1:1:bin:/bin:/sbin/nologin 3:daemon:x:2:2:daemon:/sbin:/sbin/nologin 4:adm:x:3:4:adm:/var/adm:/sbin/nologin 5:lp:x:4:7:lp:/var/spool/lpd:/sbin/nologin 6:sync:x:5:0:sync:/sbin:/bin/sync 7:shutdown:x:6:0:shutdown:/sbin:/sbin/shutdown 8:halt:x:7:0:halt:/sbin:/sbin/halt 9:mail:x:8:12:mail:/var/spool/mail:/sbin/nologin 11:operator:x:11:0:operoator:/rt:/sbin/nologin 12:operator:x:11:0:operoooooator:/rt:/sbin/nologin [[email protected]
/* */ test1]# grep -niA2 root 1.txt 1:root:x:0:0:root:/Root:/bin/bash 2-bin:x:1:1:bin:/bin:/sbin/nologin 3-daemon:x:2:2:daemon:/sbin:/sbin/nologin -- 10:operator:x:11:0:operator:/Root:/sbin/nologin 11-operator:x:11:0:operoator:/rt:/sbin/nologin 12-operator:x:11:0:operoooooator:/rt:/sbin/nologin [[email protected] test1]# grep -niB2 root 1.txt 1:root:x:0:0:root:/Root:/bin/bash -- 8-halt:x:7:0:halt:/sbin:/sbin/halt 9-mail:x:8:12:mail:/var/spool/mail:/sbin/nologin 10:operator:x:11:0:operator:/Root:/sbin/nologin [[email protected] test1]# grep -niC2 root 1.txt 1:root:x:0:0:root:/Root:/bin/bash 2-bin:x:1:1:bin:/bin:/sbin/nologin 3-daemon:x:2:2:daemon:/sbin:/sbin/nologin -- 8-halt:x:7:0:halt:/sbin:/sbin/halt 9-mail:x:8:12:mail:/var/spool/mail:/sbin/nologin 10:operator:x:11:0:operator:/Root:/sbin/nologin 11-operator:x:11:0:operoator:/rt:/sbin/nologin 12-operator:x:11:0:operoooooator:/rt:/sbin/nologin


▎grep/egrep命令的高級用法:配合正則

技術分享


以上用法在shell腳本中比較常見,需要經常練習,熟能生巧。


本文出自 “亂碼時代” 博客,請務必保留此出處http://juispan.blog.51cto.com/943137/1944215

[CentOS 7系列]grep/egrep