A large amount of my
ls use is for recent files/directories - either created same day, or within the past week. I figured I'd create a couple of aliases so I don't keep getting a screenful when I only want a handful.
The perfect solution would be if I could simply splice the -newer option from
find into the
ls command (retaining all of ls's functionality), but failing that I've been looking at other ways to achieve this.
To rule out the likely question: why not use
-ls option to
find? e.g.
find -maxdepth 1 -newermt "7 days ago" -ls
The -ls option gives equivalent to "
ls -dils" but I want "
ls -Flptr --color" by default, plus the ability to use other functionality of ls as and when required, which isn't available with that method.
After a bunch of fiddling, I came up with this - it adds a tab-delimited timestamp before the actual time definition, which awk can filter/compare against a passed in timestamp, and then remove before printing the line:
Code:
alias lsweek="f(){ ls -Flptr --color --quoting-style=shell-escape --time-style='+%t%F%t%a %e %b %H:%M' \"\$@\" | awk -v lastweek=\$(date -d '7 days ago' +'%F') -F \$'\t' 'BEGIN{OFS=\"\"}{ if (lastweek<=\$2){\$2=\"\";print} }' ;};f "
I needed to add
--quoting-style=shell-escape to ensure any filenames with newlines don't get misreported.
Here's a non-alias version of the same thing, with escaped line-breaks added for readability:
Code:
f(){
ls -Flptr --color --quoting-style=shell-escape --time-style='+%t%F%t%a %e %b %H:%M' "$@" \
| awk -v lastweek=$(date -d '7 days ago' +'%F') -F $'\t' \
'BEGIN{OFS=""}{ if (lastweek<=$2){$2="";print} }'
};f
Two downsides:
* It requires output in long listing format to work.
* Colours needs to be manually turned off if sending to a file/etc.
Neither of those are major problems, but would still be nice to have fixes/workarounds.
Or point out if I've missed anything?
Maybe there's another less hacky way to achieve this?