[CentOS 7系列]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]