简体   繁体   中英

Linux SED RegEx replace, but keep wildcards

If I have a string that contains this somewhere (Foo could be anything):

<tag>Foo</tag>

How would I, using SED and RegEx, replace it with this:

[tag]Foo[/tag]

My failed attempt:

echo "<tag>Foo</tag>" | sed "s/<tag>\(.*\)<\\/tag>/[tag]\1[\\/tag]"

Your regex is missing the terminating /

$ echo "<tag>Foo</tag>" | sed "s/<tag>\(.*\)<\\/tag>/[tag]\1[\\/tag]/"
[tag]Foo[/tag]

With this you can replace all types of tags and don't have to be tag specific.

$echo "<tag>Foo</tag>" | sed "s/[^<]*<\([^>]*\)>\([^<]*\)<\([^>]*\)>/[\1]\2[\3]/"

hope this helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM