noober
noober

Reputation: 1505

using sed or awk to double quote comma separate and concatenate a list

I have the following list in a text file:

10.1.2.200
10.1.2.201
10.1.2.202
10.1.2.203

I want to encase in "double quotes", comma separate and join the values as one string.

Can this be done in sed or awk?

Expected output:

"10.1.2.200","10.1.2.201","10.1.2.202","10.1.2.203","10.1.2.204"

Upvotes: 1

Views: 825

Answers (4)

dawg
dawg

Reputation: 103754

The easiest is something like this (in pseudo code):

  1. Read a line;
  2. Put the line in quotes;
  3. Keep that quoted line in a stack or string;
  4. At the end (or while constructing the string), join the lines together with a comma.

Depending on the language, that is fairly straightforward to do:

With awk:

$ awk 'BEGIN{OFS=","}{s=s ? s OFS "\"" $1 "\"" : "\"" $1 "\""} END{print s}' file
"10.1.2.200","10.1.2.201","10.1.2.202","10.1.2.203"

Or, less 'wall of quotes' to define a quote character:

$ awk 'BEGIN{OFS=",";q="\""}{s=s ? s OFS q$1q : q$1q} END{print s}' file

With sed:

$ sed -E 's/^(.*)$/"\1"/' file | sed -e ':a' -e 'N' -e '$!ba' -e 's/\n/,/g'
"10.1.2.200","10.1.2.201","10.1.2.202","10.1.2.203"

(With Perl and Ruby, with a join function, it is easiest to push the elements onto a stack and then join that.)

Perl:

$ perl -lne 'push @a, "\"$_\""; END{print join(",", @a)}' file
"10.1.2.200","10.1.2.201","10.1.2.202","10.1.2.203"

Ruby:

$ ruby -ne 'BEGIN{@arr=[]}; @arr.push "\"#{$_.chomp}\""; END{puts @arr.join(",")}' file
"10.1.2.200","10.1.2.201","10.1.2.202","10.1.2.203"

Upvotes: 3

Ed Morton
Ed Morton

Reputation: 203229

$ awk '{o=o (NR>1?",":"") "\""$0"\""} END{print o}' file
"10.1.2.200","10.1.2.201","10.1.2.202","10.1.2.203"

Upvotes: -2

karakfa
karakfa

Reputation: 67467

here is another alternative

sed 's/.*/"&"/' file | paste -sd,

"10.1.2.200","10.1.2.201","10.1.2.202","10.1.2.203"

Upvotes: 1

Kent
Kent

Reputation: 195039

awk -F'\n' -v RS="\0" -v OFS='","' -v q='"' '{NF--}$0=q$0q' file

should work for given example.

Tested with gawk:

kent$  cat f
10.1.2.200
10.1.2.201
10.1.2.202
10.1.2.203

kent$  awk -F'\n' -v RS="\0" -v OFS='","' -v q='"' '{NF--}$0=q$0q' f
"10.1.2.200","10.1.2.201","10.1.2.202","10.1.2.203"

Upvotes: 0

Related Questions