如何使用sed保持输入引号的存在?

时间:2017-01-24 14:17:41

标签: bash sed

我有一个简短的bash脚本来替换文件中一行中的uuid:

#!/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"

它产生几乎正确的输出,但省略了引号:

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

如何加上引号?

3 个答案:

答案 0 :(得分:1)

很高兴你得到它的工作!这是另一种方式,不涉及eval(因为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"

输出:

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

答案 1 :(得分:1)

这是一个sh版本

#!/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"

答案 2 :(得分:-1)

我通过将cmd =行更改为此来解决了我自己的问题:

cmd='echo $ProductCode | sed -r "s/$uuidPtn/$newguid/"'
感谢人们的目光。