iT邦幫忙

2025 iThome 鐵人賽

DAY 11
0
Security

從0基礎開始起飛,一起一步步踏入資安系列 第 11

[ Day 11 ] 你今天想查些檔案嗎? Linux指令 - grep

  • 分享至 

  • xImage
  •  

這次要來介紹很好用的查詢工具,grep ( global regular expression )。

grep 是 Linux/Unix 系統中最常用的文字搜尋工具之一,用於在檔案或標準輸入中尋找符合某個「pattern (字符串) 」的行,並輸出那些行。

用法 : grep [options] "pattern" [file]

引號可加可不加,單雙引號皆可

基本用法 :

grep "hello" file.txt   # 在file.txt 中查找含有字符串"hello"的行
grep "hello" file1 file2 file3   #可一次找多個
grep "hello" *.txt   #萬用字元也可以用

pipe管線用法 :

cat file.txt | grep "hello"  #在file.txt 中查找含有字符串"hello"的行
ls /etc/ | grep network   #在/etc下找尋檔名含有network的檔案

常用參數 ( options ) :

-i : 忽略大小寫

-n : 顯示行號

-H : 顯示檔名(多檔搜尋時)

-h : 不顯示檔名(多檔搜尋時)

-r : 遞迴搜尋 ( 搜尋整個目錄與子目錄 )

grep -r "pattern" [path]   #用來搜尋目錄、資料夾
grep -r "pattern" /path/to/directory

-v : 反向匹配(顯示不符合的行)

-c : 只輸出匹配行數

-l : 只列出有匹配的檔名

-L : 只列出無匹配的檔名

-s : 不顯示錯誤

其他小技巧 :

-A N : After,顯示匹配行後 N 行

-B N : Before,顯示匹配行前 N 行

-C N : Context,顯示匹配行前後 N 行

-m N : 最多輸出 N 行匹配後停止

顏色標示 :

--color=auto : 將成功匹配的部分文字用顏色標示出來

grep --color=auto [options] "pattern" [file]

生氣的老魔法使
https://ithelp.ithome.com.tw/upload/images/20250911/20177897qy6hRNKQiS.jpg


上一篇
[ Day 10 ] Linux指令 - cp / help / clear
下一篇
[ Day 12 ] 你知道怎麼find你想要的東西嗎? Linux指令 - find
系列文
從0基礎開始起飛,一起一步步踏入資安13
圖片
  熱門推薦
圖片
{{ item.channelVendor }} | {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言