bash - Insert with sed -


i start this:

{"allowed","20863962"} 

and insert label: , value: looks this:

{ label: "allowed", value: "20863962" } 

i tried sed, replace, instead of insert.

echo "{"allowed","20863962"}" | sed 's/a/label: /' | sed 's/[0-9]/value: /' 

output

{label: llowed,value: 0863962} 

you got asked for, wasn't intended.

first off, output of echo is:

{allowed,20863962} 

because shell strips double quotes out. correct input sed, use:

echo '{"allowed","20863962"}' 

then sed command drops characters, not mention not handling double quotes, , being highly specific current data. more general solution be:

sed 's/{\("[^"]*"\),\("[^"]*"\)}/{ label: \1, value: \2 }/' 

this looks 2 strings inside double quotes within { , } comma separating them , saves strings (using \(...\)) use \1 , \2.

$ echo '{"allowed","20863962"}'| sed 's/{\("[^"]*"\),\("[^"]*"\)}/{ label: \1, value: \2 }/' { label: "allowed", value: "20863962" } $ 

if general regex general, simpler technique use multiple replacements, can decide how importance attach space after open brace and, more particularly, before close brace:

$ echo '{"allowed","20863962"}' | > sed -e 's/{/{ label: /' -e 's/,/, value: /' -e 's/}/ }/' { label: "allowed", value: "20863962" } $ 

the difference between 2 in number of substitute operations , complexity. in sense, single-substitute operation concentrates on strings , fixes surroundings; multiple-substitute operation concentrates on surroundings , fixes up.


we 'rescue' code using this. note there no reason run sed twice in context.

sed -e 's/"a/label: &/' -e 's/"[0-9]/value: &/' 

this finds double quote , a , replaces label: "a because & means 'what matched'. second replacement. not insert space after { or before }, may ok.

$ echo '{"allowed","20863962"}' | sed -e 's/"a/label: &/' -e 's/"[0-9]/value: &/' {label: "allowed",value: "20863962"} $ 

were using format, i'd omit spaces after colons, that's me...


Comments

Popular posts from this blog

image - ClassNotFoundException when add a prebuilt apk into system.img in android -

I need to import mysql 5.1 to 5.5? -

Java, Hibernate, MySQL - store UTC date-time -