MABeatty1978
MABeatty1978

Reputation: 115

Adding double quotes to beginning, end and around comma's in bash variable

I have a shell script that accepts a parameter that is comma delimited,

-s 1234,1244,1567

That is passed to a curl PUT json field. Json needs the values in a "1234","1244","1567" format.

Currently, I am passing the parameter with the quotes already in it: -s "\"1234\",\"1244\",\"1567\"", which works, but the users are complaining that its too much typing and hard to do. So I'd like to just take a comma delimited list like I had at the top and programmatically stick the quotes in.

Basically, I want a parameter to be passed in as 1234,2345 and end up as a variable that is "1234","2345"

I've come to read that easiest approach here is to use sed, but I'm really not familiar with it and all of my efforts are failing.

Upvotes: 2

Views: 4545

Answers (5)

karakfa
karakfa

Reputation: 67567

awk to the rescue!

$ awk -F, -v OFS='","' -v q='"' '{$1=$1; print q $0 q}' <<< "1234,1244,1567"

"1234","1244","1567"

or shorter with sed

$ sed -r 's/[^,]+/"&"/g' <<< "1234,1244,1567"

"1234","1244","1567"

translating this back to awk

$ awk '{print gensub(/([^,]+)/,"\"\\1\"","g")}' <<< "1234,1244,1567"

"1234","1244","1567"

Upvotes: 3

Sundeep
Sundeep

Reputation: 23707

easy to do with sed

$ echo '1234,1244,1567' | sed 's/[0-9]*/"\0"/g'
"1234","1244","1567"
  • [0-9]* zero more consecutive digits, since * is greedy it will try to match as many as possible
  • "\0" double quote the matched pattern, entire match is by default saved in \0
  • g global flag, to replace all such patterns

In case, \0 isn't recognized in some sed versions, use & instead:

$ echo '1234,1244,1567' | sed 's/[0-9]*/"&"/g'
"1234","1244","1567"


Similar solution with perl

$ echo '1234,1244,1567' | perl -pe 's/\d+/"$&"/g'
"1234","1244","1567"


Note: Using * instead of + with perl will give

$ echo '1234,1244,1567' | perl -pe 's/\d*/"$&"/g'
"1234""","1244""","1567"""
""$ 

I think this difference between sed and perl is similar to this question: GNU sed, ^ and $ with | when first/last character matches

Upvotes: 1

James Brown
James Brown

Reputation: 37464

Using sed:

$ echo 1234,1244,1567 | sed 's/\([0-9]\+\)/\"\1\"/g'
"1234","1244","1567"

ie. replace all strings of numbers with the same strings of numbers quoted using backreferencing (\1).

Upvotes: 0

anubhava
anubhava

Reputation: 786291

You can do this in BASH:

$> arg='1234,1244,1567'

$> echo "\"${arg//,/\",\"}\""
"1234","1244","1567"

Upvotes: 5

Jean-Fran&#231;ois Fabre
Jean-Fran&#231;ois Fabre

Reputation: 140307

you can use this:

echo QV=$(echo 1234,2345,56788 | sed -e 's/^/"/' -e 's/$/"/' -e 's/,/","/g')

result:

echo $QV
"1234","2345","56788"

just add double quotes at start, end, and replace commas with quote/comma/quote globally.

Upvotes: 1

Related Questions