markdown-it
demo
Delete
Submit
clear
permalink
```bash # with color grep --color "pattern" file.txt # show file name and line grep -Hn "pattern" file.txt # skip binary file grep -I "pattern" file.txt # find all java in src ang grep "getName" find src/ -name *.java | xargs grep --color -Hn "getName" {} #登錄成功的日期、用戶名、IP grep "Accepted " /var/log/auth.log | awk '{print $1,$2,$3,$9,$11}' #統計一下登錄成功的IP有哪些 grep "Accepted " /var/log/auth.log | awk '{print $11}' | sort | uniq -c | sort -nr | more #統計了下日誌,發現大約有126254次登錄失敗的記錄,確認伺服器遭受暴力破解 grep -o "Failed password" /var/log/auth.log|uniq -c #輸出登錄爆破的第一行和最後一行,確認爆破時間範圍: grep "Failed password" /var/log/secure|head -1 #著色 grep alias grep='grep -n --color=auto' #進一步定位有哪些IP在爆破? ipentity="(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)" grep "Failed password" /var/log/secure|grep -E -o "$ipentity\.$ipentity\.$ipentity\.$ipentity"|uniq -c | sort -nr # 匹配行上下兩行都顯示 grep -C 2 --color 'apple' file.txt # 匹配行以下兩行都顯示 grep -A 2 --color 'apple' file.txt # 匹配行以上兩行都顯示 grep -B 2 --color 'apple' file.txt ``` # 從 A檔案中找出 不存在於 B檔案中 的行並輸出到另一份檔案中 你可以使用 Bash 搭配 `grep` 或 `comm` 來從 A 檔案中找出 **不存在於 B 檔案中的行**,也就是: ``` A - B ``` --- ### ✅ 方法一:使用 `grep`(適合不太大的文字檔) ```bash grep -Fvx -f B.txt A.txt > only_in_A.txt ``` --- ### 🔍 說明: - `-F`:逐字比對,不用正規表示法(效率更高) - `-v`:反向選擇(只保留不匹配的) - `-x`:整行比對(不是子字串) - `-f B.txt`:拿 B.txt 的內容當作篩選條件 - `A.txt`:從這裡找出「不在 B.txt 裡」的行 - `>`:把結果輸出到 `only_in_A.txt` --- ### ✅ 方法二:使用 `comm`(更快但需要排序) ```bash comm -23 <(sort A.txt) <(sort B.txt) > only_in_A.txt ``` --- ### 🔍 說明: - `comm` 會比較兩個「**已排序**」的檔案 - `-23`:隱藏「只在 B」和「兩者皆有」的行,保留「只在 A」的行 - `<(sort A.txt)` 和 `<(sort B.txt)`:先排序兩個檔案 - 結果輸出到 `only_in_A.txt` --- ### 🆚 小比較: | 方法 | 優點 | 缺點 | |------|------|------| | `grep -Fvx -f` | 不需排序、容易理解 | 效能較差 | | `comm -23` | 效能較好、適合大檔 | 必須先排序(可能影響順序) | ---
html
source
debug
Fork me on GitHub