Search code examples
linuxbashtouchls

How to touch all files that are returned by a sorted ls?


If I have the following:

ls|sort -n 

How would I touch all those files in the order of the sorted files? Something like:

ls|sort -n|touch

What would be the proper syntax? Note that I need to sort touch the files in the exact order they're being sorted -- as I'm trying to sort these files for a FAT reader with minimal metadata reading.


Solution

  • ls -1tr | while read file; do touch "$file"; sleep 1; done
    

    If you want to preserve distance in modification time from one file to the next then call this instead:

    upmodstamps() {
        oldest_elapsed=$(( $(date +%s) - $(stat -c %Y "`ls -1tr|head -1`") ))
        for file in *; do
            oldstamp=$(stat -c %Y "$file")
            newstamp=$(( $oldstamp + $oldest_elapsed ))
            newstamp_fmt=$(date --date=@${newstamp} +'%Y%m%d%H%M.%S')
            touch -t ${newstamp_fmt} "$file"
        done
    }
    

    Note: date usage assumes GNU