0

im trying to switch the no part from the below text to yes using this sed command but doesnt seem to figure it out. Any help would be greatly appreciated!

command: sed -E "s@<wodle name="docker-listener">\n\s+<disabled>(no)<\/disabled>@yes@g" /etc/test.txt

text in test.txt

<wodle name="docker-listener">
    <disabled>no</disabled>
</wodle>

<wodle name="example">
    <disabled>no</disabled>
</wodle>

UPDATE: Im in a better shape now with the below command, but the problem is that even if sed does not find a match im still get a return code of 0 and not the defined 100. Any clues how to fix this?

sed -E "N;!{q100};s@<wodle name=\"docker-listener\">\n\s+<disabled>no@<wodle name=\"docker-listener\">\n <disabled>yes@g"

antonisnyc
  • 13
  • 4
  • 2
    Please [Don't Parse XML/HTML With Regex.](https://stackoverflow.com/a/1732454/3776858). I suggest to use an XML/HTML parser (xmlstarlet, xmllint ...). – Cyrus Aug 12 '22 at 23:21
  • sed normally works on a single line so embedded `\n`won't match unless you tell sed to read multiple lines into the pattern space – jhnc Aug 12 '22 at 23:23
  • sed '// s/no/yes/' – Haru Suzuki Aug 13 '22 at 09:44

1 Answers1

1
sed  'H;1h;$!d;x;{/(<wodle name="docker-listener">\n[ ]*<disabled>)no(<\/disabled>)/!q100; s//\1yes\2/}' -E file; echo $?

0

sed  'H;1h;$!d;x;{/(<wodle name="docker-listener">\n[ ]*<disabled>)yes(<\/disabled>)/!q100; s//\1yes\2/}' -E file; echo $?

100

Since you insisted on matching \n and [[:space:]]; Storing entire file in buffer is only solution to match \n.

H;1h;$!d;x --> Store entire file in pattern buffer

/<wodle name="docker-listener">\n[ ]*<disabled>yes<\/disabled>/ --> Match for pattern

!{q100} --> sets exit code 100 if pattern not found else 0

s/// ---> will do actual replace

Haru Suzuki
  • 142
  • 10
  • hey thank you for your reply! The first one wont do because i have many similar blocks, the second one works but i still have the same problem of not returning a non `0` code when NOT replacing anything. The below still returns `0` when not replacing `sed -i 'H;1h;$!d;x;!{q100};s@\(\n[ ]*\)yes\(\)@\1yes\2@' /etc/test2.txt` – antonisnyc Aug 13 '22 at 14:27
  • check again new answer – Haru Suzuki Aug 13 '22 at 15:52
  • Thank you for saving me hours of researching! Do you know as to why the `"` dont work tho? Im curious and i had a feeling that was a big part of the issue... e.g. `sed "H;1h;$!d;x;{/(\n[ ]*)yes(<\/disabled>)/!q100; s//\1yes\2/}" -E i; echo $? ` – antonisnyc Aug 13 '22 at 16:47
  • because " " will not escape ! which is used for history substitution. Try 1) Change ! to "\!" or 2) set +H to disabled history expansion – Haru Suzuki Aug 14 '22 at 04:44