2

I want to arrange following list into specific format

Current:

42.53e-12
43.64e-12
45.78e-12
49.86e-12
57.87e-12
73.68e-12
105.3e-12

Needed

"42.53e-12, 43.64e-12, 45.78e-12, 49.86e-12, 57.87e-12, 73.68e-12, 105.3e-12"

All the numbers separated by commas and the list enclosed in quotes.

  • 1
    The output shows comma and space separators , , not just commas. – agc Feb 11 '18 at 18:52
2

Using awk:

awk '{printf (NR>1)?", "$0:"\""$0} END {print "\""}' infile

Or in another way:

awk '$1="\""$1' RS= ORS="\"\n" OFS=', ' infile

Or with combination of echo and sed commands (assuming there is no whitespaces in your file where shell word splitting is happening on that here)

sed 's/ /, /g' <(echo \"$(<infile)\")
  • awk '$1="\""$1' RS= ORS="\"\n" OFS=', ' infile gives no quotes at the end of the line. – cHiRaG Feb 11 '18 at 19:30
2
  1. Pure POSIX sh, (since it loads no external programs, this is fastest for small files, if dash is the current shell):

    n='"'; while read x; do n="$n$x, "; done < file; echo ${n%,*}\"
    
  2. Pure bash, (fastest for small files, if bash is the current shell):

    n=$(<file); echo \"${n//
    /, }\"
    
  3. Pure sed:

    sed -n 'H;${g;s/\n/, /g;s/, $//;s/, \(.*\)/"\1"/p}' file
    
  4. Shell tools:

    /bin/echo -e \"$(xargs printf "%s, " < file)'\b\b"'
    
1

A few approaches to reach the goal:

paste + sed solution:

paste -d',' -s file | sed 's/,/, /g; s/^\|$/"/g'

python solution:

python -c 'import sys; print("\""+", ".join(i.strip() for i in sys.stdin)+"\"")' <file

The output (for both approaches):

"42.53e-12, 43.64e-12, 45.78e-12, 49.86e-12, 57.87e-12, 73.68e-12, 105.3e-12"
1

Using Perl (on input from the file list.txt):

$ perl -e 'printf "\"%s\"\n", join ", ", map { chomp; $_ } <>' list.txt
"42.53e-12, 43.64e-12, 45.78e-12, 49.86e-12, 57.87e-12, 73.68e-12, 105.3e-12"

map is used to apply chomp; $_ on each line of input. chomp will remove the newline character and the $_ at the end will make the modified line the output of map for that input line.

join joins (concatenates) the array that map produced, inserting ,␣ (comma-space) between each element.

printf prints the concatenated string with " at start and end. The string is outputted with a newline at the very end.


Variation using print instead of printf:

perl -e 'print "\"", (join ", ", map { chomp; $_  } <>), "\"\n"' list.txt
0
awk 'BEGIN{ ORS=""; pre="\""}{print pre $0; pre=","}END{ORS="\n";print "\""}'
0

A pure sed solution:

sed '${H;g;s/\n//g;b};s/^.*$/&, /;H;d' infile
  • The OP specified surrounding double quotes, but this code doesn't output those. – agc Feb 12 '18 at 15:03

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.