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.

Β· Β· 1 Β· 0 Β· 0

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.

@fleegman There's other stuff around it that'll live in shell, repeated a lot. Input corpus may be hundreds of lines. It needs to be a little performant.

So a new perl every call's a bad move, wc takes nanoseconds. I'd have to write the outer part also in Perl, or in that case more likely Python or Scheme, to justify launching an interpreter.

@mdhughes Well that's unfortunate. shell is a horrendous language to try to write in. The fact that you can't reduce that trivial little function to a one-liner exemplifies.

@fleegman Oh, it can be a one-liner, except the N assignment. But it's barely readable now, even if you know zsh. Beats tens of lines of C or hundreds of ASM, as I did in the day.

@mdhughes I admit I don't know the peculiarities of zsh; I'm used to bash and ksh, which are blecherous. while loops fork? whose idea was this? πŸ˜›

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.