My goal is deceptively simple (at least to me). I wish to take the output of ls -l
or ls -lh
and select just one field.
I am looking for this to be as bulletproof as possible, by which I mean, assume that filenames can have a variable number of spaces, not everything in the field has the same length, etc.
Bonus points for having a script that will take the name of the the field (or even just a field number), and then return the contents of the field.
I want to turn
into:
Try
ls -l | awk '{print $7}'
.awk
selects columns so it's perfect for this task.Never parse ls. Use GNU
find
. Or if portability isn't important,stat(1)
.For reading data other than lists of filenames line-by-line and splitting into fields, see: BashFAQ/001
There are no methods to reliably read a newline-delimited list of filenames that make sense under most circumstances.
You may fetch the specific column in shell like:
or
awk
as shown in @Corey answer,cut -c44-45
would also work after adjustment (sincels
has fixed columns) , or whatever else, however the main problem is that it won't be reliable and bulletproof (e.g. on Unix it may be$6
, not$7
, and it changes depending on arguments) making it not machine-friendly therefore it is not recommended to parsels
command at all.The best is to use different available commands such as
find
orstat
, which can provide relevant options to format the output as you need. For example:To return column of only days of modifications, try this example:
It's worth to note that GNU
stat
could have different options to BSDstat
, so it still won't be bulletproof across different operating systems.