Basically I get line from ls -la
command:
-rw-r--r-- 13 ondrejodchazel staff 442 Dec 10 16:23 some_file
and want to get size of file (442). I have tried cut
and sed
commands, but was unsuccesfull. Using just basic UNIX tools (cut, sed, awk...), how can i get specific column from stdin, where delimiter is / +/
regexp?
If you want to do it with cut
you need to squeeze the space first (tr -s ' '
) because cut
doesn't support +
. This should work:
ls -la | tr -s ' ' | cut -d' ' -f 5
It's a bit more work when doing it with sed
(GNU sed):
ls -la | sed -r 's/([^ ]+ +){4}([^ ]+).*/\2/'
Slightly more finger punching if you use the grep alternative (GNU grep):
ls -la | grep -Eo '[^ ]+( +[^ ]+){4}' | grep -Eo '[^ ]+$'
Parsing ls
output is harder than you think. Use a dedicated tool such as stat
instead.
size=$(stat -c '%s' some_file)
One way ls -la some_file | awk '{print $5}'
could break is if numbers use space as a thousands separator (this is common in some European locales).
See also Why You Shouldn't Parse the Output of ls(1).
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