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
Benjamin W.
  • 46,058
  • 19
  • 106
  • 116
Vicky
  • 801
  • 7
  • 7

3 Answers3

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
$
John Kugelman
  • 349,597
  • 67
  • 533
  • 578
AKX
  • 152,115
  • 15
  • 115
  • 172
  • Thanks for your response. Actually, I want to retain quotes. "my-email","another-email","third-email" – Vicky Aug 09 '18 at 13:34
  • 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`. – Benjamin W. Aug 09 '18 at 13:42
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).

Benjamin W.
  • 46,058
  • 19
  • 106
  • 116
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.

Graham
  • 1,631
  • 14
  • 23