Sait
Sait

Reputation: 19855

Vim remove part of line in a file

I have a big file contains many lines in the following format,

<SomeString1>Key1</SomeString>
<SomeString2>Key2</SomeString>
<SomeString3>Key3</SomeString>
...

I want to remove the tags, and the output should look like,

 Key1
 Key2
 Key3
 ...

Algorithmically, I should write something like:

For all lines:
   Remove all string before character `>`
   Remove all string after character `</`

Upvotes: 7

Views: 6699

Answers (2)

ShellFish
ShellFish

Reputation: 4551

Simply use a replace :

:%s/<[^>]*>//g

This will apply the s (substitution) command for each line (%) and remove all <...> sequences for the entire line (g).

There are many situations in which these commands come in handy, especially using regex. You can find more information about it here.

Upvotes: 12

Beebs
Beebs

Reputation: 21

These two commands should do the trick:

:%s/<\w*>//
:%s/<\/\w*>//

The first replaces all the opening tags with nothing. The second replaces all the closing tags with nothing. <\w*> matches any number of alphanumeric characters between < and > and <\/\w*> matches any number of alphanumeric characters between </ and >.

Edit: a simpler way:

:%s/<.\{-}>//g

Note that this:

:%s/<.*>//g

Won't work because the * is "greedy" and will match the whole line. \{-} is the non-greedy equivalent. Read more about greediness here: http://vimregex.com/#Non-Greedy

Upvotes: 2

Related Questions