Test
Test

Reputation: 51

How to delete the text in a file except the words I needed using VIM

I have an XML file like this:

<text>
<A>12</A>
<B>13</B>
</text>

<text>
<A>14</A>
<B>15</B>
</text>

Now I want delete all the text in the file except the words in tag A. That is, the file should contain:

12
14

How can I achieve this?

Upvotes: 3

Views: 113

Answers (3)

jinfield
jinfield

Reputation: 312

:%s/\_.\{-}<A>\([^<]*\)<\/A>\_.\{-}>$/\1\r/

Gets everything but the final /text tag in one fell swoop :-) Fun stuff!!

Upvotes: 0

John Weldon
John Weldon

Reputation: 40739

You can do it in two commands (on one line if you like)

:g!/.*<A>[^<]*<\/A>.*/d
:%s/<A>\([^<]*\)<\/A>/\1/g

one line: (separate commands with a vertical bar |)

:g!/.*<A>[^<]*<\/A>.*/d | :%s/<A>\([^<]*\)<\/A>/\1/g

This will remove the blank lines...

Upvotes: 2

Colin Newell
Colin Newell

Reputation: 3163

:%s/^.\{-}\(<A>\(.*\)<\/A>\)\?.*$/\2/g

That assumes you have the same magic mode as me of course ;) It doesn't remove the blank lines.

Upvotes: 0

Related Questions