Reputation: 821
I want to input multiple strings.
For example:
abc
xyz
pqr
and I want output like this (including quotes) in a file:
"abc","xyz","pqr"
I tried the following code, but it doesn't give the expected output.
NextEmail=","
until [ "a$NextEmail" = "a" ];do
echo "Enter next E-mail: "
read NextEmail
Emails="\"$Emails\",\"$NextEmail\""
done
echo -e $Emails
Upvotes: 1
Views: 915
Reputation: 1759
If you can withstand a trailing comma, then printf
can convert an array, with no loop required...
$ readarray -t a < <(printf 'abc\nxyx\npqr\n' )
$ declare -p a
declare -a a=([0]="abc" [1]="xyx" [2]="pqr")
$ printf '"%s",' "${a[@]}"; echo
"abc","xyx","pqr",
(To be fair, there's a loop running inside bash, to step through the array, but it's written in C, not bash. :) )
If you wanted, you could replace the final line with:
$ printf -v s '"%s",' "${a[@]}"
$ s="${s%,}"
$ echo "$s"
"abc","xyx","pqr"
This uses printf -v
to store the imploded text into a variable, $s
, which you can then strip the trailing comma off using Parameter Expansion.
Upvotes: 0
Reputation: 52132
With sed and paste
:
sed 's/.*/"&"/' infile | paste -sd,
The sed command puts ""
around each line; paste
does serial pasting (-s
) and uses ,
as the delimiter (-d,
).
If input is from standard input (and not a file), you can just remove the input filename (infile
) from the command; to store in a file, add a redirection at the end (> outfile
).
Upvotes: 1
Reputation: 168957
This seems to work:
#!/bin/bash
# via https://stackoverflow.com/questions/1527049/join-elements-of-an-array
function join_by { local IFS="$1"; shift; echo "$*"; }
emails=()
while read line
do
if [[ -z $line ]]; then break; fi
emails+=("$line")
done
join_by ',' "${emails[@]}"
$ bash vvuv.sh
my-email
another-email
third-email
my-email,another-email,third-email
$
Upvotes: 1