1. 程式人生 > >grep命令-Linux字串查詢

grep命令-Linux字串查詢

最近用到了平時經常用的grep,但遇到全字匹配和排除檔案,排除目錄的操作。觸及到知識盲區,特此去學習瞭解記錄一下。如果遇到其他用法在新增編輯。

文章目錄

1 背景

在Linux環境中,有時會遇到程式報了些問題,但有沒有標註所在位置,這裡就需要一種方法去把它找出來。

比如在node中使用了new buffer()這個操作就帶來了下列警告,有忘記了在哪裡寫了這個語句,所以想在當前目錄找到 “new Buffer(” 這個語句在哪個檔案哪一行。

node:9296) [DEP0005] DeprecationWarning: Buffer() is deprecated due to security and usability issues. Please use the Buffer.alloc(), Buffer.allocUnsafe(), or Buffer.from() methods instead.

2 grep使用

Linux grep命令用於查詢檔案裡符合條件的字串。
grep指令用於查詢內容包含指定的範本樣式的檔案,如果發現某檔案的內容符合所指定的範本樣式,預設grep指令會把含有範本樣式的那一列顯示出來。

2.1 基本用法

grep “待搜尋內容” “檔案路徑”

grep "port" app.js   // 查詢結果:   module.exports = app;

在 app.js檔案中查詢包含port的行

grep -n "port" app.js   // 查詢結果:   121:module.exports = app;

在 app.js檔案中查詢包含port的行,並列印行號。
-n引數 列印行號

2.2 查詢目錄

grep -n -r "port" . 

查詢當前目錄下包含port的行,並列印行號。
-r 查詢目錄,且會遞迴整個目錄。

2.3 通配查詢

grep -n port *.js //app.js:121:module.exports = app;   
                            //errors.js:41:module.exports = {

在當前目錄下 所有js檔案中查詢帶port的行

2.4 全字匹配

grep -n  -w "port" app.js  

只顯示全字符合的行,必須完全相同。

2.5 排除指定檔案

grep -n  --exclude=app.js port *.js
--exclude=檔名 排除指定檔案

搜尋結果排除指定檔案中的內容

2.6 排除指定目錄

grep -n  --exclude-dir=node_modules port *.js
 --exclude-dir=檔案目錄名(路徑)

搜尋結果排除指定資料夾中的內容

2.7 grep配合管道篩選資料

sudo netstat -tlnp | grep "node"
netstat -tlnp 顯示當前linux 網路狀態

本人就經常使用上條語句檢視node 佔用的埠和node的PID。

3 參考連結

http://www.runoob.com/linux/linux-comm-grep.html
https://www.cnblogs.com/pengdonglin137/p/3569218.html