Code Golfing Split String in Bash


Let us play a little golfing game. Given a single line of N space separated numbers from STDIN, one must output those numbers on N lines.

So far, I came up with the three following bash solutions :

  • xargs -n1 (9)
  • tr \ \\n (8)
  • fmt -1 (6)

Can anyone do better? I am eager to learn new tricks


Posted 2017-07-06T13:04:27.020

Reputation: 79

Question was closed 2017-07-17T07:27:30.693

7It is frowned upon to limit the language. – Leaky Nun – 2017-07-06T13:04:51.913

1It is also frowned upon to restrict the format of the input and the output. – Leaky Nun – 2017-07-06T13:05:05.713

3Welcome to PPCG. You should perhaps change this to a tips question. – officialaimm – 2017-07-06T13:07:14.833

in bash, I think the minimum is 5, because you will have at least 2 chars for a command (single-char commands are not a thing IMO), a space, and at least 2 chars for an arg. And so I think, you are already 1st in line with fmt -1. – V. Courtois – 2017-07-06T13:08:57.057

1Can the space-separated numbers be input as a string (enclosed with quote symbols)? Can the output lines contain leading spaces with the numbers right-aligned? Can we use functions that take a string and output a string with newlines? – Luis Mendo – 2017-07-06T16:41:26.497

Can I get the the numbers from program arguments? In Tcl: puts [join $argv \n]demo

– sergiol – 2017-07-06T20:13:11.090

Your tr command needs an extra space: tr \␣␣\\n (9), not tr \␣\\n (8). – Anders Kaseorg – 2017-07-07T00:44:52.780

@V.Courtois 1-byte commands are definitely a thing, and, well, hypothetically, a 1-byte command can do the job... – Erik the Outgolfer – 2017-07-08T13:18:47.510

@ErikTheOutgolfer oh okay, sorry then – V. Courtois – 2017-07-08T18:45:55.057

1bash or shell? all these are shell commands - not part of bash language. – philcolbourn – 2017-07-12T09:51:49.710



Bash (22)

read X;printf %d\\n $X  (thanks to manatwork but without literal NL)

30 read -aX;printf "%d\n" ${X[*]} 26 read X;echo -e ${X// /\n} 28 printf "%d\n" $(</dev/stdin) 27 printf "%d\n" $(</dev/fd/0) 26 printf %d\n $(</dev/fd/0) 23 read X;printf "%d\n" $X


Posted 2017-07-06T13:04:27.020

Reputation: 501

1As it says the input will contain just 1 line of numbers, read X;printf '%d ' $X is enough. (Where is a literal line break.) – manatwork – 2017-07-12T10:33:50.050