grep の出力をファイル サイズで並べ替えますか? (bash)

grep の出力をファイル サイズで並べ替えますか? (bash)

特定のディレクトリにある特定の文字列を 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
}

出力をシェルエスケープすることで任意のパスをサポートします。

前提条件: GNU sed/ grep、Bash 4。

関連情報