Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get nth column with regexp delimiter [duplicate]

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?

like image 611
Ondra Avatar asked Dec 10 '12 16:12

Ondra


Video Answer


2 Answers

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 '[^ ]+$'
like image 123
Thor Avatar answered Sep 30 '22 20:09

Thor


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).

like image 37
tripleee Avatar answered Sep 30 '22 20:09

tripleee