DomainsFeatured
DomainsFeatured

Reputation: 1506

Match Anything In Between Strings For Linux Grep Command

I have read the post grep all characters including newline but I not working with XML so it's a bit different with my Linux command.

I have the following data:

Example line 0</span>
<tag>Example line 1</tag>
<span>Example line 1.5</span>
<tag>
Example line 2
</tag>
Example line 3
<span>Example line 4</span>

Using this command cat file.txt | grep -o '<tag.*tag>\|^--.*' I get:

<tag>Example line 1</tag>

However, I want the output to be:

<tag>Example line 1</tag>
<tag>Example line 2</tag>

How can I match anything between the strings, including the newline?

Note: I need to used <tag and tag> as strings because other files can contain multiple tags and text in between the lines. Will update sample data to show that.

Upvotes: 2

Views: 826

Answers (2)

John1024
John1024

Reputation: 113814

Consider this test file:

$ cat file2
Example line 0</span>
<tag>Example line 1</tag>
<span>Example line 1.5</span>
<tag>
Example line 2
</tag>
Example line 3
<span>Example line 4</span>

This produces the output that you want (requires GNU sed):

$ sed -z 's|\n||g; s|</tag>|&\n|g; s|[^\n]*<tag>|<tag>|; s|\n[^\n]*<tag>|\n<tag>|g; s|\n[^\n]*$|\n|' file2
<tag>Example line 1</tag>
<tag>Example line 2</tag>

Limitation: Note that processing XML-like text with non-specialized tools can be quite fragile.

Upvotes: 0

anubhava
anubhava

Reputation: 784898

This is easier done with gnu-awk using </tag> as record separator:

awk -v RS='</tag>' 'RT {gsub(/\n/, ""); print $0 RT}' file

<tag>Example line 1</tag>
<tag>Example line 2</tag>

Upvotes: 2

Related Questions