Windows XP Windows 7 Windows 2003 Windows Vista Windows 綜合教學 Linux 系統教學
Windows 10 Windows 8 Windows 2008 Windows NT Windows Server 電腦軟體教學
您现在的位置: Windows教程網 >> Windows教程 >  >> Linux 系統教學 >> Linux 教學

Linux 三劍客 grep、awk、sed 核心用法速查手冊

編輯:Linux 教學

grep:模式匹配過濾

引號規則

  • 雙引號 "pattern":防止 Shell 解釋特殊字符,支援變數展開 "$VAR",可搜尋多詞 "jet plane"。
  • 單引號 'pattern':原義字面,變數不展開,正則元字符需轉義。
  • 反引號 `cmd`:命令替換(輸出作為參數)。

常用選項

選項功能
-c僅輸出匹配行計數
-i忽略大小寫
-h多檔不顯示檔名
-l多檔僅列出含匹配的檔名
-n顯示行號
-v反向匹配(非匹配行)
-s抑制錯誤訊息

行首行尾與空行

grep -n '^$' file        # 空行(行首即行尾)
grep -n '^abc' file      # 以 abc 開頭
grep -n 'abc$' file      # 以 abc 結尾

特殊字符轉義

grep '\.' file           # 匹配字面點
grep 'my\.conf' file     # 匹配 my.conf

多檔與目錄

grep "pattern" *.log     # 當前目錄所有 .log
grep -r "pattern" /dir   # 遞迴搜尋目錄

進程過濾經典

ps -ef | grep telnet | grep -v grep

awk:欄位提取與報表生成

基本語法

awk [-F 分隔符] '程式碼' 檔案...
  • 預設分隔符:空白(含 Tab)。
  • -F: 指定冒號分隔(如 /etc/passwd)。

欄位引用

  • $0:整行。
  • $1, $2 ... $NF:第 1、2 ... 最後一欄。

經典範例

# 第 5 欄含 user 的行
awk -F: '$5 ~ /user/ {print $0}' /etc/passwd

# 取得本機 IP(假設輸出含 inet addr:)
ifconfig | awk '/inet addr:/ {print $2}' | awk -F: '{print $2}'

sed:流編輯器(非互動)

行定址

sed -n '2p' file           # 第 2 行
sed -n '1,3p' file         # 1-3 行
sed -n '$p' file           # 最後一行
sed -n '/pattern/p' file   # 匹配行

插入/附加新行

sed '/pattern/a\new line' file  # 匹配行後插入
sed '/pattern/i\new line' file  # 匹配行前插入
sed '5a\new line' file          # 第 5 行後插入

刪除

sed '1d' file        # 刪第 1 行
sed '1,3d' file      # 刪 1-3 行
sed '/pattern/d' file # 刪匹配行

替換(s///)

sed 's/old/new/g' file          # 全行替換
sed 's/old/new/2' file          # 只替第 2 次出現
sed -n 's/old/new/gp' file      # 只輸出被替換的行
Copyright © Windows教程網 All Rights Reserved