Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

Most of the time I avoid parsing ls, but I haven't found a reliable way to do this one:

  latest="$(ls -1 $pattern | sort --reverse --version-sort | head -1)"
Anyone got a better solution?


This ones a hard one. Since "--version-sort" isn't standard anyways, lets assume we can use flags which are common to BSD and GNU. Furthermore, lets assume bash or zsh so we can use "read -d ''".

In that case, how about:

  IFS='' read -d '' latest < <(find $pattern -prune -print0 | sort -z --reverse --version-sort)


This should work with any arbitrary filename:

    latest=$(printf '%s\0' <glob> | sort -zrV | head -zn1)
or with long args:

    latest=$(printf '%s\0' <glob> | sort --zero-terminated --reverse --version-sort | head --zero-terminated --lines 1


What unix is this on? Neither the mac nor gnu manpages have a -z or --zero-terminated option for head.



Yay! Glad to see zero termination flags in more places.

EDIT: The linux manpages I read were from die.net, which it looks like were from 2010, guess I'll have to avoid them in the future. I checked FreeBSD, OpenBSD, and Mac man page to make sure, and unfortunately none of them support the -z flag yet.




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: