Split paragraph into lines in ZSH

How can I take a multi-line string in zsh and split it into an array of strings, each of which contains one string?

In particular, I want to take the output of cal

      June 2010     
Su Mo Tu We Th Fr Sa
       1  2  3  4  5
 6  7  8  9 10 11 12
13 14 15 16 17 18 19
20 21 22 23 24 25 26
27 28 29 30

and turn it into

("      June 2010     " "Su Mo Tu We Th Fr Sa" "       1  2  3  4  5"  " 6  7  8  9 10 11 12" "13 14 15 16 17 18 19" "20 21 22 23 24 25 26" "27 28 29 30")

What is a zsh array.


My ultimate goal is to take the output of another command and place it next to each other, so if I had

a
b
c

and

d
e
f

I would end with

a d
b e
c f
+3
source share
2 answers

Here is an example of replacing a process that will work in zsh and Bash. It uses the Unix / Linux tool pasteto place two calendars side by side as a demo.

$ paste <(cal 6 2009) <(cal 6 2010)

     June 2009               June 2010
Su Mo Tu We Th Fr Sa    Su Mo Tu We Th Fr Sa
    1  2  3  4  5  6           1  2  3  4  5
 7  8  9 10 11 12 13     6  7  8  9 10 11 12
14 15 16 17 18 19 20    13 14 15 16 17 18 19
21 22 23 24 25 26 27    20 21 22 23 24 25 26
28 29 30                27 28 29 30

To answer your question directly:

saveIFS=$IFS; IFS=$'\n'; array=($(cal 6 2010)); IFS=$saveIFS

Which also works in Bash.

+5

zsh

array=( ${(s.
.)"$(cal)"} )

, eval:

eval $'array=( ${(s.\n.)"$(cal)"} )'

(s.smth.) ( , . IFS, (s.:::.) :::, IFS=':::' :). eval (s), (s.\n.) "n".

+3

Source: https://habr.com/ru/post/1752304/


All Articles