萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 伺服器教學

Linux Shell 文本搜尋實戰:find/xargs/grep 多種組合技

面對 GB 級日誌文件,下載到本地分析極其低效。本文總結三類在伺服器端直接搜尋文本的高效組合,並提供一個功能完整的通用搜尋腳本。

方法一:find + xargs + grep(標準管道)

# 目錄遞歸搜尋
find /var/log -type f | xargs grep "ERROR"

# 指定文件搜尋
find /var/log/app.log | xargs grep "timeout"

優點:處理海量文件不會超過命令行長度限制。
注意:文件名含空格時需 find ... -print0 | xargs -0 grep ...。

方法二:grep 遞歸搜尋(最簡潔)

# 僅當前目錄
grep "pattern" /path/*

# 遞歸子目錄(-r)
grep -r "pattern" /path/

# 忽略大小寫(-i)
grep -ri "pattern" /path/

# 顯示行號(-n)
grep -rn "pattern" /path/

方法三:通用搜尋腳本

整合遞歸、大小寫、多路徑、排除自身等功能:

#!/bin/bash
# find_str.sh  用法:find_str.sh 路徑 關鍵字 [-r] [-i]

if [ $# -lt 2 ]; then
    echo "Usage: $(basename $0) path keyword [-r] [-i]"
    exit 1
fi

path=$1
keyword=$2
shift 2

dir_op=""   # -r 遞歸
lu_op=""    # -i 忽略大小寫

for opt in "$@"; do
    case $opt in
        -r) dir_op="-r" ;;
        -i) lu_op="-i" ;;
        *) echo "Invalid option: $opt"; exit 1 ;;
    esac
done

grep_file() {
    local file=$1
    local str=$2
    local out
    out=$(grep -n $lu_op "$str" "$file")
    if [ -n "$out" ] && [ "$file" != "$0" ]; then
        echo "$file: $out"
    fi
}

find_str() {
    local target=$1
    local str=$2
    if [ -d "$target" ]; then
        for f in "$target"/*; do
            if [ "$dir_op" = "-r" ] && [ -d "$f" ]; then
                find_str "$f" "$str"
            elif [ -f "$f" ]; then
                grep_file "$f" "$str"
            fi
        done
    elif [ -f "$target" ]; then
        grep_file "$target" "$str"
    fi
}

find_str "$path" "$keyword"

使用範例

# 遞歸搜尋 /var/log 包含 "failed" 的行(忽略大小寫)
./find_str.sh /var/log failed -r -i

# 單文件精確搜尋
./find_str.sh /etc/nginx/nginx.conf upstream

效能建議

  • 大目錄優先用 grep -r,內部已優化目錄遍歷
  • 需正則表達式時加 -E 或改用 egrep
  • 二進制文件自動跳過,若需強制搜尋加 -a
  • 配合 --include/--exclude 限制文件類型:grep -r --include="*.log" "error" /var/log
copyright © 萬盛學電腦網 all rights reserved