Hrm. Can anyone code-golf this shell script smaller? I want a random line from a a stream of lines in zsh.

N=`echo $L|wc -l`
I=$(( ($RANDOM - 1) % $N + 1))
echo $P

First pass was head -$I|tail -1, which is stupid but traditional if you're using sh.

I should name more variables l & I and use a lot of pipes. I use Fira Code, I got 99 problems but readability ain't one.

Obviously easier if I just pull it into Perl or whatever, but that's another 10ms I could be doing something else in.

I have a bad habit of using scripts as test input to themselves, and there's nothing more confusing than this nonsense script.

@mdhughes Are you sure Perl is a loser here? One thing it WON'T be doing is spawning yet another processs and writing all those lines to it, just to get a line count. ffs.

You trying to golf this, or just doing it in perl, which is faster?
@l = `whatever`; print $l[ rand @l ];


@mdhughes Of course, to do this The Right Way, you wouldn't load the entire set of lines into memory anyway.

Β· Β· 0 Β· 0 Β· 0
Sign in to participate in the conversation

Fosstodon is an English speaking Mastodon instance that is open to anyone who is interested in technology; particularly free & open source software.