How to get nth column with regexp delimiter

Ondra picture Ondra · Dec 10, 2012 · Viewed 10.1k times · Source

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?

Answer

Thor picture Thor · Dec 10, 2012

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 '[^ ]+$'