2

I've got a folder with several thousand files with names like ousjgforuigor-TIMESTAMP.txt

The timestamp is a standard Unix timestamp (e.g. 1543932635). Is there an easy way to list only files with a filename-timestamp > a provided one?

The number of characters before the timestamp is variable, but the name always ends with -TIMESTAMP.txt

I could write a bash script to do this, but that seems like overkill.

1 Answer 1

2

Using zsh's expression-as-a-glob-qualifier,

t=1543951252 zsh -c 'datefilter() { ts=${REPLY##*-}; ts=${ts%*.txt}; ((ts >= $t)) }; print -l *-<->.txt(+datefilter)'

The overall command (towards the end) is print -l, which prints each argument on a separate line. Well, the overall command is a presumed bash shell call to zsh that sets the environment variable t to some given value. Instead of printing the filenames, you could put them in an array or delete them or do anything else you want with them.

The glob qualifier *-<->.txt picks up potentially-matching filenames -- ones that begin with anything (*), followed by a dash (-), followed by any range of numbers (zsh's range operator <->), followed by .txt; that globbing is then sent to the glob qualifier (+datefilter), which is a call to the corresponding function.

The datefilter function takes the incoming filename (in $REPLY) and prunes it down to the timestamp value. It returns true if that timestamp value is greater than or equal to the given timestamp in t. Files that succeed in that test are kept as filenames; the rest are dropped.

You could do something similar in bash by manually looping over the glob:

for f in *-*.txt
do 
  ts=${f##*-}
  ts=${ts%.txt}
  [[ ts -ge t ]] && printf '%s\n' "$f"
done

Although the bash wildcard * could pick up stray filenames such as foo-bar.txt where bar is not required to be a number. You'd have to hard-code in some assumptions otherwise, such as:

for f in *-[0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9].txt; do # ...

or

for f in *-[0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9][0-9]*.txt; do # ...

to force some number of digits to appear between the dash and the period.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .