0

I want to split a string on a delimiter in zsh on MacOS 11.6.1. I looked at the following questions How do I split a string on a delimiter in Bash?

I tried to reproduce its 2 most upvoted answers as follows:

IN="bla@some.com;john@home.com"
IFS=';' read -ra ADDR <<< "$IN"
for i in "${ADDR[@]}"; do
  # process "$i"
done
IN="bla@some.com;john@home.com"
while IFS=';' read -ra ADDR; do
  for i in "${ADDR[@]}"; do
    # process "$i"
  done
done <<< "$IN"

but get the following output : bad option: -a

IN="bla@some.com;john@home.com"
arrIN=(${IN//;/ })
echo ${arrIN[1]}                  # Output: john@home.com

but get the following output : bla@some.com john@home.com instead of john@home.com

What am I doing wrong?

Charles Duffy
  • 280,126
  • 43
  • 390
  • 441
ecjb
  • 5,169
  • 12
  • 43
  • 79
  • 7
    `bash` and `zsh` are 2 different shells, so "in bash in zsh" doesn't make much sense. The error suggests you're using `zsh` in which case it would be `arrIN=(${(s[;])IN})` – jqurious Aug 15 '23 at 16:33
  • Many thanks @jqurious! that worked! (I removed the "bash" from the question) – ecjb Aug 15 '23 at 20:48
  • "bash" was still in title and tagging; I've removed it more thoroughly. – Charles Duffy Aug 15 '23 at 21:12
  • sorry about that. thank you @CharlesDuffy – ecjb Aug 15 '23 at 21:23
  • According to the zsh man pages, `read` does not have an `-a` option. Perhaps you mean `-A`: _-A ... The first name is taken as the name of an array and all words are assigned to it_. – user1934428 Aug 16 '23 at 06:02

1 Answers1

1

You can use awk and avoid different shells particularities

awk '{sub(";","\n"); print}' <<<"bla@some.com;john@home.com" | xargs process
Diego Torres Milano
  • 65,697
  • 9
  • 111
  • 134
  • many thanks for your answer @DiegoTorresMilano. But when I tried your code (namely `awk '{sub(";","\n"); print}' <<<"bla@some.com;john@home.com" | xargs process`), I got the following error message: `xargs: process: Not a directory` – ecjb Aug 15 '23 at 20:46
  • I thought you are invoking something called `process` from you example `# process "$i"` – Diego Torres Milano Aug 16 '23 at 01:45
  • Thanks for your your comment @DiegoTorresMilano. I replaced `process` with `echo` and got `bla@some.com john@home.com` (instead of `bla@some.com`) – ecjb Aug 16 '23 at 07:31
  • Add `-L 1` to `xargs` to take 1 line at a time – Diego Torres Milano Aug 16 '23 at 14:44