• Uncategorized

About linux : Remove-first-3-columns-from-ls

Question Detail

If I do ls -o I get

-rw-rw-r-- 1 louise     347967 Aug 28  2017 Screenshot from 2017-08-28 09-33-01.png
-rw-rw-r-- 1 louise     377739 Aug 29  2017 Screenshot from 2017-08-29 10-39-49.png
-rw-rw-r-- 1 louise     340682 Aug 29  2017 Screenshot from 2017-08-29 10-40-02.png

I really want to remove the first 3 columns, so I get

347967 Aug 28  2017 Screenshot from 2017-08-28 09-33-01.png
377739 Aug 29  2017 Screenshot from 2017-08-29 10-39-49.png
340682 Aug 29  2017 Screenshot from 2017-08-29 10-40-02.png

ls can’t do this, it seems. There are other questions here at SO about removing multiple columns, but not from the beginning.

Question Answer

ls is an interactive tool, whose output is not supposed to be parsed.

Consider using an alternative tool such as stat (GNU version recommended):

stat -c '%s %y %n' *

The output isn’t quite the same but you have full control over the format. stat --help gives more information about the possible format sequences.

With GNU stat you can also use --printf to add escape characters such as newlines or tabs in the format string, to make parsing easier:

stat --printf '%s\t%Y\t%n\n' *

%Y (last modification, seconds since Epoch) is more readily suited to parsing than %y (human-readable).

This would still break in cases where the filename contained a newline, so depending on how you plan on using this information, you may want to use a \0 instead of a \n at the end of the format string and process records terminated with a null-byte instead of a newline.

Alternatively, you may find it easier to just loop through the files and call stat on them one by one, extracting whatever you need:

for file in *; do
    read -r size modified name < <(stat '%s %Y %n' "$file")
    # do whatever with $size, $modified and $name here
done

Assuming you go with the loop-based approach, you can convert the date to any format you want using date, for example:

date -d @"$modified" +'%b %d %H:%m'

You may also like...

Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.