0

I'm not very good on regex, I need to search for

<anyword/> and repace with <anyword></anyword>

Like <book/> to <book></book>

4 Answers 4

3

It sounds like you're trying to parse XML with regexes, which is usually a bad idea — XML is much more complicated than it may initially seem (what happens when you need to replace <a b="c"/> with <a b="c"></a>? what about non-ASCII element names?) — but if you're certain that what you've described is exactly what you need, then you can write:

perl -pe 's{<(\w+)/>}{<$1></$1>}g' < input_file > output_file

or:

sed 's|<\([^[:space:]][^[:space:]]*\)/>|<\1></\1>|g' < input_file > output_file
Sign up to request clarification or add additional context in comments.

1 Comment

thank you the sed version worked.. I only removed the [:space:] check... also I'm sure that the file I need to edit has only the <name /> or <name>value</name> tags...
1

Use

sed -i 's|<\([[:alpha:]][[:alpha:]]*\)/>|<\1></\1>|g' $input_file

to change the file in-line (that's what the -i is for). Careful: The -i is a GNU extension.

To be POSIX compliant and edit the file inline (on any *IX system), use this:

echo '/<[[:alpha:]][[:alpha:]]*\/>/g\
s/<\([[:alpha:]][[:alpha:]]*\)\/>/<\1><\/\1>/g
wq' | ed $input_file

See the POSIX standard on sed, ed, and regular expressions.

Comments

0

The regular expression to match your tags would be:

<(\w+)/>

By using the capture group, you could create the new tags like this:

<\1></\1>

Comments

0

This might work for you:

echo '<book/>' | sed 's|<\([^/]*\)/>|<\1></\1>|'
<book></book>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.