Suppose that you have to find the name of the 4th smallest (non-hidden) file in the directory
What is the right command to do this? Suppose I'm a guy who only knows ls -l, head, tail, line, and awk '{print}' statement.
From man ls: -S sorts the output by size descending, -r reverses the order of the output
So my solution would look like
ls -rS | sed -n '4p'
or, alternatively
ls -rS | awk 'NR==4'
Parsing ls is not safe because it is difficult and error prone to handle strange characters like spaces and newlines in filenames.
I would recommend using the following approach which is more robust since it uses null-terminated line endings.
count=0
while IFS= read -r -d '' line; do
((++count == 4)) && echo "${line#* }" && break
done < <(find . -type f -maxdepth 1 -printf '%s %p\0' | sort -zn)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With