0

I want to grep for a certain string, in a certain directory. Then I want to sort the files by size (number of bytes would be fine). The files are .php files, though I don't think other non-php files would have the string I'm looking for. How do I do this?

I got the grep part:

grep -rl "foostring" ~/myfolder

1 Answer 1

2

Files in order of decreasing size:

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
}

Supports any paths by shell-escaping the output.

Prerequisites: GNU sed/grep, Bash 4.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .