1

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
0

3 Answers 3

1

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
$
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for your response. Actually, I want to retain quotes. "my-email","another-email","third-email"
You could change the last line to join_by '","' "\"${emails[@]}\"" for the quotes, and the while loop could be (Bash 4.0 or newer) readarray -t emails < /dev/stdin.
1

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).

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.