stack user
stack user

Reputation: 863

How to preserve presence of quote marks from input with sed?

I have a short bash script to replace a uuid in a line in a file:

#!/bin/sh

alpha="0-9A-F"
uuidPtn="[$alpha]{8}-[$alpha]{4}-[$alpha]{4}-[$alpha]{4}-[$alpha]{12}"
ProductCode="\"ProductCode\" = \"8:{0059DDB5-D384-46F9-BBFD-0004A8C39732}\""

newguid=`uuidgen`
newguid="${newguid^^}"

cmd="echo $ProductCode | sed -r s/$uuidPtn/$newguid/"

echo "$ProductCode"
eval "$cmd"

It produces almost correct output, but with the quotation marks omitted:

"ProductCode" = "8:{0059DDB5-D384-46F9-BBFD-0004A8C39732}"
ProductCode = 8:{A4B1D092-1C56-44F3-B096-34B67A5F39B1}

How can I include the quotation marks?

Upvotes: 2

Views: 281

Answers (3)

mug896
mug896

Reputation: 2025

This is a sh version

#!/bin/sh

alpha="0-9A-F"
uuidPtn="[$alpha]{8}-[$alpha]{4}-[$alpha]{4}-[$alpha]{4}-[$alpha]{12}"
ProductCode="\"ProductCode\" = \"8:{0059DDB5-D384-46F9-BBFD-0004A8C39732}\""

newguid=`uuidgen`
newguid=$(echo "${newguid}" | tr a-z A-Z)

ChangedCode=$(echo "$ProductCode" | sed -r s/$uuidPtn/$newguid/)

echo "$ProductCode"
echo "$ChangedCode"

Upvotes: 1

cxw
cxw

Reputation: 17041

Glad you got it working! Here's another way, which does not involve eval (since eval is evil):

#!/bin/bash

alpha="0-9A-F"
uuidPtn="[$alpha]{8}-[$alpha]{4}-[$alpha]{4}-[$alpha]{4}-[$alpha]{12}"
ProductCode="\"ProductCode\" = \"8:{0059DDB5-D384-46F9-BBFD-0004A8C39732}\""

newguid=`uuidgen`
newguid="${newguid^^}"

#cmd="echo "$ProductCode" | sed -r s/$uuidPtn/$newguid/"  ## Not this

echo "$ProductCode"
#eval "$cmd"                                       ## Not this either

#                    v                    v whole pattern quoted
changedcode=$(sed -r "s/$uuidPtn/$newguid/" <<<"$ProductCode")
#           ^^         command substitution                  ^
#                    here-strings for input ^^^^^^^^^^^^^^^^^
echo "$changedcode"

Output:

"ProductCode" = "8:{0059DDB5-D384-46F9-BBFD-0004A8C39732}"
"ProductCode" = "8:{6094CF73-E23E-4655-B4A8-DAA57BE7EF72}"

Upvotes: 1

stack user
stack user

Reputation: 863

I solved my own problem by changing the cmd= line to this:

cmd='echo $ProductCode | sed -r "s/$uuidPtn/$newguid/"'

thanks for the eyes on though folks.

Upvotes: -1

Related Questions