0

I have a file that needs to take the contents within tags. For example:

<Model500>
ABC
BCD 
CDE
</Model500>


<Model500>
123
234
345
</Model500>

I would like to extract the contents within

<Model500>
</Model500>

using 'sed'

So it would look like

ABC
BCD
CDE

123
234
345

I have attempted this using

sed -e 's/<Model>\,/</Model>/p' file.txt

But the special characters are causing issues. Any advice? Thank you.

  • Is this XML? Because there's tool for that. – thrig Sep 12 '16 at 20:49
1

If the input is XML, then it is best to use an XML-specific tool.

Method 1

One method for including a / in a sed regex is to escape it with a backslash:

$ sed -ne '/<Model500>/,/<\/Model500>/p' file.txt
<Model500>
ABC
BCD 
CDE
</Model500>
<Model500>
123
234
345
</Model500>

The expression /<Model500>/,/<\/Model500>/ specifies a range of lines. The range starts with a line that matches <Model500> and ends with a line that matches <\/Model500>. Since we are specifying a range, not a substitute command, the expression does not start with s.

Method 2

If you don't want to escape it, you can use a different delimiter:

$ sed -ne '\|<Model500>|,\|</Model500>|p' file.txt
<Model500>
ABC
BCD 
CDE
</Model500>
<Model500>
123
234
345
</Model500>

Here, we used | as the delimiter. To signal that a delimiter other than / is being used in a range, the first one should be escaped: \|.

  • 1
    I am used to the Method 1 format and it makes the most sense to me. Thanks! This really helps understand formatting techniques. – keyboard_solo Sep 12 '16 at 21:14
0

Since the string </Model> contains the / character, you need to either escape it in your sed expression or use a different character to delimit your sed expression. Fortunately sed can use any single character to delimit the expression, so you simply have to pick one that doesn't appear in your input.

On a more general note, sed probably isn't the best choice for the task at hand. It appears that you are parsing an XML file, so you should probably leverage a library built for XML parsing rather than hacking something together with sed. See this post for a description of why that's a bad idea.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.