Vim remove part of line in a file

6.1k views Asked by At

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 `</`
2

There are 2 answers

0
ShellFish On BEST ANSWER

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.

0
Beebs On

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