give me a bash command that recursively lists all the files in the file tree under the…
- User
give me a bash command that recursively lists all the files in the file tree under the working directory, sorts them by size, and displays the file size. if it's relatively easy, i would also like a horizontal bar that is of proportional length next to each. if it's not easy, skip that part. it's optional
Assistant
Here's a bash command that recursively lists all files in the current directory and its subdirectories, sorts them by size, displays the file size, and includes a horizontal bar proportional to the file size:
max_size=$(find . -type f -printf "%s\n" | sort -n | tail -1); find . -type f -printf "%s %p\n" | sort -n | awk -v max_size=$max_size '{ size = $1; file = substr($0, index($0, " ") + 1); bar_length = (size / max_size) * 50; bar = ""; for (i = 0; i < bar_length; i++) { bar = bar "#"; } printf "%10d %s %s\n", size, bar, file; }'This command works as follows:
find . -type f -printf "%s\n"lists all files with their sizes in bytes.sort -nsorts these sizes numerically.tail -1gets the largest size, which is stored inmax_size.find . -type f -printf "%s %p\n"lists all files with their sizes and paths.sort -nsorts this list by file size.awkprocesses each line to:- Extract the size and file path.
- Calculate the length of the bar proportional to the file size relative to the maximum size.
- Generate the bar using
#characters. - Print the size, bar, and file path.
If you're not using GNU
find, you can use this alternative command which usesstat(note thatstat -cis also GNU-specific):max_size=$(find . -type f -exec stat -c "%s" {} \; | sort -n | tail -1); find . -type f -exec stat -c "%s %n" {} \; | sort -n | awk -v max_size=$max_size '{ size = $1; file = substr($0, index($0, " ") + 1); bar_length = (size / max_size) * 50; bar = ""; for (i = 0; i < bar_length; i++) { bar = bar "#"; } printf "%10d %s %s\n", size, bar, file; }'For systems without GNU extensions, a more portable but less efficient approach would involve using
lsandawkwith more complex parsing, but that's beyond the scope here. The above commands should work on most Linux systems with GNU utilities.
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.