shell - How do I split a string on a delimiter in Bash? -
i have string stored in variable:
in="bla@some.com;john@home.com" now split strings ; delimiter have:
addr1="bla@some.com" addr2="john@home.com" i don't need addr1 , addr2 variables. if elements of array that's better.
after suggestions answers below, ended following after:
#!/usr/bin/env bash in="bla@some.com;john@home.com" mails=$(echo $in | tr ";" "\n") addr in $mails echo "> [$addr]" done output:
> [bla@some.com] > [john@home.com] there solution involving setting internal_field_separator (ifs) ;. not sure happened answer, how reset ifs default?
re: ifs solution, tried , works, keep old ifs , restore it:
in="bla@some.com;john@home.com" oifs=$ifs ifs=';' mails2=$in x in $mails2 echo "> [$x]" done ifs=$oifs btw, when tried
mails2=($in) i got first string when printing in loop, without brackets around $in works.
you can set internal field separator (ifs) variable, , let parse array. when happens in command, assignment ifs takes place single command's environment (to read ). parses input according ifs variable value array, can iterate over.
ifs=';' read -ra addr <<< "$in" in "${addr[@]}"; # process "$i" done it parse 1 line of items separated ;, pushing array. stuff processing whole of $in, each time 1 line of input separated ;:
while ifs=';' read -ra addr; in "${addr[@]}"; # process "$i" done done <<< "$in"
Comments
Post a Comment