依檔案大小對 grep 輸出進行排序? (重擊)

依檔案大小對 grep 輸出進行排序? (重擊)

我想在某個目錄中 grep 找到某個字串。然後我想按大小對文件進行排序(位元組數就可以了)。這些文件是 .php 文件,但我認為其他非 php 文件不會包含我正在尋找的字串。我該怎麼做呢?

我得到了 grep 部分:

grep -rl "foostring" ~/myfolder

答案1

文件依大小遞減順序排列:

matching_files_by_size() {
    local matching_paths path
    mapfile -d '' -t matching_paths < <(grep --files-with-matches --null --recursive "$@")
    for path in "${matching_paths[@]}"
    do
        printf '%s\t%q\n' "$(du --bytes -- "$path" | cut --fields=1)" "$path"
    done | sort --key=1 --numeric-sort --reverse | cut --fields=2
}

透過對輸出進行 shell 轉義來支援任何路徑。

先決條件:GNU sed/ grep、Bash 4。

相關內容