Linux教程網
Linux教程網
Linux教程網
您现在的位置: Linux教程網 >> UnixLinux >  >> Linux基礎 >> Linux技術

Linux 字串搜尋指令 grep 詳解

grep 是 Linux 中強大的文字搜尋工具,可使用正則表達式搜尋文字,並輸出符合的行。其全稱為 Global Regular Expression Print,使用權限為所有使用者。

基本格式與參數

格式:grep [options]。常用參數:-c 只輸出符合行數;-I 不區分大小寫;-h 多檔案時不顯示檔名;-l 只輸出符合的檔名;-n 顯示行號;-s 不顯示錯誤;-v 顯示不符合的文字。

正則表達式常用符號:\ 忽略特殊含義;^ 匹配行首;$ 匹配行尾;[ ] 匹配單一字元;[ - ] 表示範圍;. 匹配任意單一字元;* 表示前一字元可出現零次或多次。

搜尋實例

在目錄中搜尋含 magic 的檔案:grep magic /usr/src/Linux/Doc/*。若目錄中有子目錄,可用 grep -r 搜尋子目錄,或用 grep -d skip 忽略子目錄。

輸出過多時,可搭配 less:grep magic /usr/src/Linux/Documentation/* | less。常用參數:grep -i pattern files 不區分大小寫;grep -l pattern files 只列出符合檔名;grep -L pattern files 列出不符合檔名;grep -w pattern files 只匹配整個單字;grep -C number pattern files 顯示上下文。

搜尋多模式:grep pattern1 | pattern2 files 可顯示符合任一模式的行;grep pattern1 files | grep pattern2 可顯示同時符合兩個模式的行。

常見用法

遍歷檔案搜尋:find . -name "*c" | xargs grep "strings"。在目錄中遞迴搜尋:grep -r youcode dir。從檔案內容搜尋:grep "被查尋的字符串" 文件名。使用正則:grep -e "正則表達式" 文件名。不區分大小寫:grep -i "被查尋的字符串" 文件名。統計行數:grep -c "被查尋的字符串" 文件名。反向搜尋:grep -v "被查尋的字符串" 文件名。

Copyright © Linux教程網 All Rights Reserved