[ask]how does sed -e 's/<[^>]*>//g' works?

I found this command, sed -e 's/<[^>]*>//g', will return the content of a line with pattern something like this, <tag1>content</tag1>..

How does this works?
What does sed -e 's/<[^>]*>//g' actually do?
What if I wanted to get content of a line with pattern something like this, [tag2]content[/tag2]?
thanks..

I don't think that will do what you describe.

 sed -e 's/pattern/replacement/g' 

is a search and replace pattern. In your example, there's no replace, and nothing will be returned.

You could use something like

sed -e 's/<\([^>]*\)>/\1/g'

to capture what's between the literal <>'s and return it.

The way that works: it could be read "find a literal < followed by 0 or more characters that are not a >, followed by a literal >, capturing the non-'>' characters and replacing the entire match with what is captured, for all instances (the meaning of the g at the end)

1 Like

thanks for answering..
when I run your command, I got different result..

echo "<tag1>content</tag1>" | sed -e 's/<\([^>]*\)>/\1/g'
tag1content/tag1

and when I run this command, I got this..

echo "<tag1>content</tag1>" | sed -e 's/<[^>]*>//g'
content

Your explanation is really helpful, because I was wondering what [, ^>, and *> means in sed..

Alternatives :wink:

# echo "<tag1>content</tag1>" | sed -e 's/<[^<]*>//g'
content
# echo "<tag1>content</tag1>" | sed -e 's/.*>\(.*\)<.*/\1/'
content
# echo "<tag1>content</tag1>" | sed -e 's/<[^<]*>//1'
content</tag1>
# echo "<tag1>content</tag1>" | sed -e 's/<[^>]*>//2'
<tag1>content

-- PowerFull Sed --

1 Like

The first sentence removes all the tags so the content remains.

$ echo "<tag1>content</tag1>" | sed 's/<[^>]*>//g'
content

To do the same with you could do this:

$ echo "[tag2]content[/tag1]" | sed 's/\[[^]]*\]//g'
content
1 Like

Huh. I could have sworn I got different results when I tested this. Now, though, it behaves as you describe. I will claim tiredness as my excuse.