Skip to main content

Stack Exchange Network

Stack Exchange network consists of 183 Q&A communities including Stack Overflow, the largest, most trusted online community for developers to learn, share their knowledge, and build their careers.

Visit Stack Exchange
Asked
Viewed 637 times
8
\$\begingroup\$

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

\$\endgroup\$
10
  • 7
    \$\begingroup\$ It is frowned upon to limit the language. \$\endgroup\$
    Leaky Nun
    –  Leaky Nun
    2017-07-06 13:04:51 +00:00
    Commented Jul 6, 2017 at 13:04
  • 1
    \$\begingroup\$ It is also frowned upon to restrict the format of the input and the output. \$\endgroup\$
    Leaky Nun
    –  Leaky Nun
    2017-07-06 13:05:05 +00:00
    Commented Jul 6, 2017 at 13:05
  • 3
    \$\begingroup\$ Welcome to PPCG. You should perhaps change this to a tips question. \$\endgroup\$
    0xffcourse
    –  0xffcourse
    2017-07-06 13:07:14 +00:00
    Commented Jul 6, 2017 at 13:07
  • 1
    \$\begingroup\$ Can 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? \$\endgroup\$
    Luis Mendo
    –  Luis Mendo
    2017-07-06 16:41:26 +00:00
    Commented Jul 6, 2017 at 16:41
  • 1
    \$\begingroup\$ bash or shell? all these are shell commands - not part of bash language. \$\endgroup\$
    philcolbourn
    –  philcolbourn
    2017-07-12 09:51:49 +00:00
    Commented Jul 12, 2017 at 9:51

1 Answer 1

1
\$\begingroup\$

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

\$\endgroup\$
1
  • 1
    \$\begingroup\$ As it says the input will contain just 1 line of numbers, read X;printf '%d␤' $X is enough. (Where ␤ is a literal line break.) \$\endgroup\$
    manatwork
    –  manatwork
    2017-07-12 10:33:50 +00:00
    Commented Jul 12, 2017 at 10:33

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.

Morty Proxy This is a proxified and sanitized view of the page, visit original site.