「 linux三劍客,最經常使用的linux命令之grep——編程三分鐘」
grep 參數解釋
在這裏爲了節省篇幅,我就不一一解釋了,只介紹一些很是經常使用的組合。
遞歸查找全部匹配的文件內容
$ grep -rl love *
dir/file3.txt
file.txt
file2.txt
複製代碼
忽略大小寫遞歸查找並帶行號輸出
$ grep -inr "It doesn’T" *
dir/file3.txt:38:It doesn’t matter where
file.txt:38:It doesn’t matter where
file2.txt:38:It doesn’t matter where
複製代碼
忽略大小寫顯示行號,顯示匹配內容和先後2行
通常用於定位日誌問題,-A 2 -B 2 也能夠替換成-C 2
$ grep -in "It doesn’T" file.txt -A 2 -B 2
file.txt-36-the way that ypu change my world
file.txt-37-when I’m with you
file.txt:38:It doesn’t matter where we're from and where file.txt-39-as long as your with me all the way file.txt-40-And the nights are long and lonely and 複製代碼
查找匹配的進程名,忽略帶grep的內容
$ ps -ef | grep -i wei
501 1807 1 0 25 519 ?? 5:29.55 /usr/bin/Weiyun -psn_0_176171
501 92256 1851 0 10:32 grep --color=auto
$ ps -ef | grep -i wei | grep -v grep
501 1807 1 0 25 519 ?? 5:29.55 /usr/bin/Weiyun -psn_0_176171
複製代碼
或邏輯查找
$ grep -E "love|change" file.txt
I love you
I love you
the way that you change my world
Love may come and love may go複製代碼
正則表達式測試
最騷的就數這個了,不用再下載一堆東西或者打開某個網頁在測試正則表達式了,好比校驗json、校驗郵箱。一個grep就搞定,是否是很方便呢?
echo coding3min@foxmail.com | grep -p "^[A-Za-z0-9\u4e00-\u9fa5]\+\@[a-zA-Z0-9_-]\+\(\.[a-zA-Z0-9_-]\+\)"
coding3min@foxmail.com複製代碼