'sed replace backslash double quote with single quote
I would like to take the following:
echo "'{\"apiVersion\":\"apps/v1\", \"kind\":\"two\"}'"
And end up with the following via using SED:
{'apiVersion':'apps/v1', 'kind':'two'}
Solution 1:[1]
Using Bash's string replace:
#!/usr/bin/env bash
a='{\"apiVersion\":\"apps/v1\", \"kind\":\"two\"}'
# Replaces all occurrences of \" with '
b=${a//\\\"/\'}
# Debug prints converted string
printf '%s\n' "$b"
Solution 2:[2]
echo '{\"apiVersion\":\"apps/v1\", \"kind\":\"two\"}'| tr -d '\\'|tr '"' "'"
echo '{\"apiVersion\":\"apps/v1\", \"kind\":\"two\"}'| sed "s/.\"/'/g"
echo '{\"apiVersion\":\"apps/v1\", \"kind\":\"two\"}'| awk '{gsub(/\\"/, "\047"); print}'
{'apiVersion':'apps/v1', 'kind':'two'}
update (new string)
echo "'{\"apiVersion\":\"apps/v1\", \"kind\":\"two\"}'"| tr -d "'"|tr '"' "'"
echo "'{\"apiVersion\":\"apps/v1\", \"kind\":\"two\"}'"| sed "s/'//g; s/\"/'/g"
echo "'{\"apiVersion\":\"apps/v1\", \"kind\":\"two\"}'"| awk '{gsub(/\047/, ""); gsub(/"/, "\047"); print}'
{'apiVersion':'apps/v1', 'kind':'two'}
{'apiVersion':'apps/v1', 'kind':'two'}
{'apiVersion':'apps/v1', 'kind':'two'}
Solution 3:[3]
UPDATE 1 : if you insist on sed
, then it's :
echo '{\"apiVersion\":\"apps/v1\", \"kind\":\"two\"}' |
sed -E 's/\\["]/\x27/g'
# BSD-sed
{'apiVersion':'apps/v1', 'kind':'two'}
echo '{\"apiVersion\":\"apps/v1\", \"kind\":\"two\"}' |
gsed -E 's/\\["]/\x27/g'
# GNU-sed
{'apiVersion':'apps/v1', 'kind':'two'}
===============================
UPDATE 2 : if you're not comfortable dealing with octal codes in awk
, then it's
gawk -e 'NF++~—-NF' FS='\\\\"' OFS="'"
{'apiVersion':'apps/v1', 'kind':'two'}
===============================
A relatively portable awk
-based solution
echo '{\"apiVersion\":\"apps/v1\", \"kind\":\"two\"}' |
gawk NF=NF FS='\\\\\42' OFS='\47'
{'apiVersion':'apps/v1', 'kind':'two'}
echo '{\"apiVersion\":\"apps/v1\", \"kind\":\"two\"}' |
gawk -Pe NF=NF FS='\\\\\42' OFS='\47'
{'apiVersion':'apps/v1', 'kind':'two'}
echo '{\"apiVersion\":\"apps/v1\", \"kind\":\"two\"}' |
gawk -ce NF=NF FS='\\\\\42' OFS='\47'
{'apiVersion':'apps/v1', 'kind':'two'}
echo '{\"apiVersion\":\"apps/v1\", \"kind\":\"two\"}' |
mawk NF=NF FS='\\\\\42' OFS='\47'
{'apiVersion':'apps/v1', 'kind':'two'}
echo '{\"apiVersion\":\"apps/v1\", \"kind\":\"two\"}' |
mawk2 NF=NF FS='\\\\\42' OFS='\47'
{'apiVersion':'apps/v1', 'kind':'two'}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Léa Gris |
Solution 2 | |
Solution 3 |