Marcx
Marcx

Reputation: 6836

Search and replace string in unix bash

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

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

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

Upvotes: 0

Views: 1127

Answers (4)

djhaskin987
djhaskin987

Reputation: 10107

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.

Upvotes: 1

potong
potong

Reputation: 58578

This might work for you:

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

Upvotes: 0

ruakh
ruakh

Reputation: 183602

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

Upvotes: 3

betabandido
betabandido

Reputation: 19704

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>

Upvotes: 0

Related Questions