繼續鳥哥的linux學習
1 grep [-A] [-B] [ -- color=auto] "搜尋的字符串" filename
參數 : -A 後面加數字,爲after的意思,除了列出該行外,後面n行也列出來
-B 後面加數字,爲berore,除了列出該行外,前面n行也列出來
例如 : dmesg 列出內核信息,用grep找不包含eth的哪行
e1000 0000:02:01.0: eth0: (PCI:66MHz:32-bit) 00:0c:29:6f:23:dc
e1000 0000:02:01.0: eth0: Intel(R) PRO/1000 Network Connection
e1000: eth0 NIC Link is Up 1000 Mbps Full Duplex, Flow Control: None
eth0: no IPv6 routers present
8021q: adding VLAN 0 to HW filter on device eth0
eth0: no IPv6 routers present
[root@localhost ~]#
包含eth的都找出來啦,並且是紅色的
例如 : 把關鍵詞所在的行的前三行和後三行都輸出來
另外 grep每次加上 --color=auto很麻煩,所以使用alias別名
在 ~/.bashrc 內加上alias grep='grep --color=auto'
再 source~/.bashrc 來立即生效
練習:
查找特定的字符串
grep -n '字符串' test.txt
-n 顯示行號
'字符串' 要匹配的字符串
若是反向選擇,則加上 v
grep -vn '字符串' test.txt
不區分大小寫 參數 i
----------------------------------------------------------------
[] 裏面是可以多選則的,代表[]中的一個字符
例如
grep -n '人[們啊]' test.txt
若不想要某個字符開頭的則使用 ^ (在[]內使用)
例如不要男開頭的
grep -n '[]^男]人' test.txt
匹配了所有的人,但是不包含男人
^與[]結合
grep -n '[^男女]人' test.txt
------------------------------------------------------------------
行首與行尾字符 ^行首 $行尾
例子:以 ^我 開頭
grep -n '^我' test.txt
以 我$ 結尾
grep -n '我$' test.txt
------------------------------------------------------------------
例如
找到空白行
grep -n '^$' test.txt
今天就到這了,明天繼續