2

So i wanted to replace the following

<duration>89</duration>

with (Expected Result or at least Shoud become this:)

\n<duration>89</duration>

so basically replace every < with \n< in regex So i figured.

sed -e 's/<[^/]/\n</g'

Only problem it obviously outputs

\n<uration>89</duration>

Which brings me to my question. How can i tell regex to mach for a character which follows < (is not /) but stop it from replacing it so i can get my expected result?

0

5 Answers 5

1

Try this:

sed -e 's/<[^/]/\\n&/g' file

or

sed -e 's/<[^/]/\n&/g' file

&: refer to that portion of the pattern space which matched

Sign up to request clarification or add additional context in comments.

1 Comment

Nice. The -E option is more portable IMHO
1

It can be nicely done with awk:

echo '<duration>89</duration>' | awk '1' RS='<' ORS='\n<'
  • RS='<' sets the input record separator to<`
  • ORS='\n<' sets the output record separator to\n<'
  • 1 always evaluates to true. An true condition without an subsequent action specified tells awk to print the record.

Comments

0
 echo "<duration>89</duration>" | sed -E 's/<([^\/])/\\n<\1/g'

should do it.

Sample Run

$ echo "<duration>89</duration>
> <tag>Some Stuff</tag>"| sed -E 's/<([^\/])/\\n<\1/g'
\n<duration>89</duration>
\n<tag>Some Stuff</tag>

Comments

0

Your statement is kind of correct with one small problem. sed replaces entire pattern, even any condition you have put. So, [^/] conditional statement also gets replaced. What you need is to preserve this part, hence you can try any of the following two statements:

sed -e 's/<\([^/]\)/\n<\1/g' file

or as pointed by Cyrus

sed -e 's/<[^/]/\n&/g' file

Cheers!

Comments

0
echo '<duration>89</duration>' | awk '{sub(/<dur/,"\\n<dur")}1'
\n<duration>89</duration>

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.