codefx
codefx

Reputation: 10502

Add double quotes to items of a comma separated list

I would like to add double quotes a directory full of files inplace. The transformation will be like below:

INSERT INTO %T (colA, colB) changes to INSERT INTO %T ("colA", "colB")

I have tried various examples using sed. I was able to get grep to identify the files and line numbers. Can you show me how to achieve this inplace without manually modifying the files?

Upvotes: 0

Views: 125

Answers (3)

user4453924
user4453924

Reputation:

Another way with awk

awk -F"(" -vOFS="(" '{gsub(/[^, )]+/,"\"&\"",$2)}1' file

Output

INSERT INTO %T ("colA", "colB")

Upvotes: 0

NeronLeVelu
NeronLeVelu

Reputation: 10039

sed '
# Filter to insert only
   /INSERT INTO/ !b
# Add first and last " inside ()
   s/(/("/
   s/)[^)]*$/")/
# add all internal " around each ,
   s/,[[:space:]]*/","/g
' YourFile

Onliner version (without filter and assuming space char as space):

sed 's/(/("/;s/)[^)]*$/")/;s/, */","/g' YourFile
  • Self explain.
  • Assume there structure is without internal () and only 1 group of ()

Upvotes: 1

Jotne
Jotne

Reputation: 41446

This may do:

awk -F"[()]" '{n=split($(NF-1),a,", *");for (i=1;i<n;i++) s=s sprintf("\"%s\", ",a[i]);s=s "\""a[n]"\"";print $1 "("s")"}'

eks:

echo 'INSERT INTO %T (colA, colB, colC)' | awk -F"[()]" '{n=split($(NF-1),a,", *");for (i=1;i<n;i++) s=s sprintf("\"%s\", ",a[i]);s=s "\""a[n]"\"";print $1 "("s")"}'
INSERT INTO %T ("colA", "colB", "colC")

Upvotes: 1

Related Questions