2

Assume I have the following example text in example.txt:

<para>This is some paragraph text
This is another line of paragraph text.
</para>

What I want to achieve: Replace all <para> and </para> tags with the null string, if the resulting line is empty, delete the line. I achieved this with the following two commands:

# remove the line that solely consist of the para tag.
$ sed -i '/^<para>$/d;/^<\/para>$/d' ./example.txt

# Replace any of the para tags with an empty string.
$ sed -i 's/<para>//g;s/<\/para>//g' ./example.txt

My question: Is it possible to achieve this in one sed command, making use of a conditional line deletion?

  • Do you care if there are more ampty lines? If so, do you want to keep them? – guillermo chamorro Dec 14 '19 at 14:11
  • @guillermochamorro I use GNU sed and I do want to keep the other empty lines. – BramAppel Dec 14 '19 at 14:18
2

If you have GNU sed, you could use the T command to branch past an empty line delete if the replacement fails:

sed 's/<\/\{0,1\}para>//g;T;/^$/d' example.txt
T label

Branch to label only if there have been no successful substitutions since the last input line was read or conditional branch was taken. The label may be omitted, in which case the next cycle is started.

With non-GNU sed it should be possible to do the same by combining t and b

sed -e 's/<\/\{0,1\}para>//g;ta;b' -e ':a;/^$/d' example.txt
0

Using GNU sed:

$ sed -nE 's|</?para>||g;/./p' file

Perform the required substitution(s) and if after that you are left with something, print it. OTW, your pattern space, aka current line, comprised only para and/or /para tags exclusively, and those records need to be suppressed.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.