Home > Back-end >  replace file context with "/" in shell
replace file context with "/" in shell

Time:01-16

my sample file is like:

# sample.txt
adc=lalalala
cmd="echo hihi && echo yoyo"
cda=lolololo

i wish to replace line of cmd like:

old=`cat ./sample.txt|grep cmd`
app=' && echo dudu"'

new=${old:0:-1}${app}

sed -i "s/${old}/${new}/g" ./sample.txt

the expect result should be

adc=lalalala
cmd="echo hihi && echo yoyo && echo dudu"
cda=lolololo

however turned out:

adc=lalalala
cmd="echo hihi cmd="echo hihi && echo yoyo"cmd="echo hihi && echo yoyo" echo yoyo cmd="echo hihi && echo yoyo"cmd="echo hihi && echo yoyo" echo dudu"
cda=lolololo

i also tried sed -i "s#${old}#${new}#g" ./sample.txt but not difference. can i get some help? thx very much

CodePudding user response:

Try something like

sed -E -i '' 's@(cmd="echo hihi && echo yoyo)"@\1 \&\& echo dudu"@' sample.txt

notice you have to escape the &.

CodePudding user response:

sed -i "/^cmd=*/c$new" ./sample.txt
  • Related