0

I’m using Zsh’s parameter expansion flags to split a string into an array.

This works:

string="one
two"
array=("${(f)string}")
echo "${array[1]}"

# Returns:
# one

This does not work:

string="one\ntwo"
array=("${(f)string}")
echo "${array[1]}"

# Returns:
# one
# two

How can we make the expansion interpret the \n as a newline?

1 Answer 1

1

The zshexpn manual covers such manipulations; one option is the e parameter expansion flag (in same section as your (f) split) but e does a whole lot of things (parameter expansion, command substitution, and arithmetic expansion) as part of making \n literal. Or maybe you do want all those manipulations to happen?

% string="a\nb" ; print -l ${(f)${(e)string}}
a
b

More exact is g which processes only escape sequences as handled by the builtin echo:

% string="a\nb" ; array=( ${(f)${(g::)string}} ) ; print $array[2]
b

Even more exact is to split only on a literal \n:

% string="a\nb" ; print -l ${(s.\\n.)string}
a
b
1
  • Thank you. Exactly what I was looking for. I did try e and g:: but in the same parenthesis as the f. I now see they had to be nested. I could swear I tried the last solution, but it may have been ps:\n:. Do note that it seems to require \n, not \\n. Commented Jul 17, 2022 at 19:41

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.