身為開發者,遲早都會在職涯中與 Linux 指令打交道。雖然我不是系統管理專家,但掌握以下 8 個核心指令,幾乎能應對絕大多數日常文本處理與排查需求。本文不求大全,只記錄實戰中最高頻的用法與管線組合技巧,助你快速上手。
假設我們有兩個檔案,分別記錄對外下單與內部流轉:
order.out.log
8:22:19 111, 1, Patterns of Enterprise Architecture, Kindle edition, 39.99
8:23:45 112, 1, Joy of Clojure, Hardcover, 29.99
8:24:19 113, -1, Patterns of Enterprise Architecture, Kindle edition, 39.99
order.in.log
8:22:20 111, Order Complete
8:23:50 112, Order sent to fulfillment
8:24:20 113, Refund sent to processing
最基礎的檢視指令,也能合併多檔:
cat order.out.log
cat order.*
輸出會將兩份日誌首尾相連,但可讀性較差,需配合後續工具。
cat order.* | sort
即可將所有紀錄按時間戳排序,讓前後文脈清晰可見。
只看特定關鍵字:
cat order.* | sort | grep Patterns
鎖定《Patterns of Enterprise Architecture》相關訂單。若要查某筆訂單完整流程,用更嚴格的正則:
cat order.* | sort | grep ":dd 113,"
避免 113 出現在價格或書名中造成誤判。
會計只需數量與價格:
cat order.* | sort | grep Patterns | cut -d"," -f2,5
輸出:1, 39.99 與 -1, 39.99,一目瞭然。
需在行尾補上訂單 ID 並加單引號:
cat order.* | sort | grep Patterns \
| sed 's/\"[0-9:]* ([0-9]*), (.*)\"/\"\2, \x27\1\x27\"/' \
| cut -d"," -f1,4,5
輸出:1, 39.99,'111'、-1, 39.99,'113'。正則邏輯:刪除時間、捕獲訂單號、保留其餘欄位、重組格式。
統計各書銷售筆數:
cat order.out.log | grep -E "(Kindle|Hardcover)" | cut -d"," -f3 | sort | uniq -c
結果:
1 Joy of Clojure
2 Patterns of Enterprise Architecture
find /Users -name "order*"
不需記得完整檔名,支援萬用字元,覆蓋 99% 搜尋場景。
cat order* | sort | less
支援 / 向前搜尋、? 向後搜尋、q 離開,搭配正則如 /113.* 秒找目標行。
這 8 個指令透過管線串聯,構成「檢視 → 排序 → 過濾 → 擷取 → 重組 → 統計 → 定位 → 瀏覽」完整鏈路,足以處理絕大多數文本分析任務,無需寫腳本即可高效落地。