-1

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

furynerd
  • 109
  • 1
  • 8
  • 1
    The `&` character has a special meaning in a sed replacement string. ["Escape a string for a sed replace pattern"](https://stackoverflow.com/questions/407523/escape-a-string-for-a-sed-replace-pattern/2705678#2705678) should explain what you need to do. – Gordon Davisson Jan 16 '23 at 01:52
  • This also looks like a variation on https://stackoverflow.com/questions/65538947/counting-lines-or-enumerating-line-numbers-so-i-can-loop-over-them-why-is-this - `sed` already knows exactly how to find the line which contains `cmd` – tripleee Jan 16 '23 at 06:07

2 Answers2

0

Try something like

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

notice you have to escape the &.

Diego Torres Milano
  • 65,697
  • 9
  • 111
  • 134
  • sadly looks doesnt work...i tried and got a error `sed: -e expression #1, char 52: invalid reference \1 on `s' command's RHS`, moreover, `old` and `new` are dynamicly changed, so i need these expressions – furynerd Jan 16 '23 at 01:42
  • my bad, see edit, `-i` is followed by an extension – Diego Torres Milano Jan 16 '23 at 01:46
  • glad to find a way works`sed -i "/^cmd=*/c$new" ./sample.txt` – furynerd Jan 16 '23 at 01:59
  • The extension after `-i` is optional (at least in GNU sed). If there is no extension, no backup file is created (see the man-page for `sed`). – user1934428 Jan 16 '23 at 11:05
  • `sed [-Ealnu] [-i extension] [-e script] ... [-f script_file] ... [file ...]` on macOS, not optional but can be empty to not create a backup file – Diego Torres Milano Jan 16 '23 at 22:43
-1

the key change should be:

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

the full shell script is:

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

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

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

furynerd
  • 109
  • 1
  • 8