Derrick Zhang
Derrick Zhang

Reputation: 21511

How to delete text after a specified symbol until the end of the line in Vim?

My data is of the form:

id|name|things that I don't care

So for each line I want to delete text after the second | symbol.

How do I do this in Vim with one command?

Note: There are actually extra pipes after the second |, since the | character is used as the delimiter for columns.

Upvotes: 12

Views: 9404

Answers (5)

ib.
ib.

Reputation: 29004

One can simply repeat the Normal-mode command that jumps to the character next to the second | symbol and deletes the rest of the text on the line, for each line in the buffer, via the :normal command:

:%norm!2f|lD

Upvotes: 11

johnny
johnny

Reputation: 657

:%s/[^|]*|[^|]*|\zs.*//

A variation of what we've already seen.

Match many "not pipe" followed by pipe, twice. Replace with nothing starting from second pipe (\zs).

Upvotes: 0

Jens
Jens

Reputation: 72747

If the "don't care" part has no pipes, then

:%s/|[^|]*$/|/

which also deals with empty "don't care" parts. And it keeps working if you add new fields before the "don't care" part.

Upvotes: 1

johnsyweb
johnsyweb

Reputation: 141928

One solution:

:%s!^\([^|]*|\)\{2\}\zs.*!!

Explanation:

  • %: on every line
  • s: subtitute
  • !: start of pattern
  • ^: start of line
  • \(: start of group
  • [^|]*: any number of non-pipe characters
  • |: followed by a pipe
  • \): end of group
  • \{2\}: match two counts of that group
  • \zs: start the pattern matching here
  • .*: any characters
  • !: end of pattern and start of replacement
  • !: end of replacement

This will leave lines with fewer than two pipes untouched and will also deal with lines that have more than the two pipes...

Before

id name things that I don't care no pipes
id|name things that I don't care one pipe
id|name|things that I don't care two pipes
id|name|things that I don't care extra pipe at line end|
id|name|things that I don't care | extra pipe mid-line
id|name|things that I don't| care| two extra pipes
name|things that I don't care missing first column and pipe
|name|things that I don't care missing first column

After:

id name things that I don't care no pipes
id|name things that I don't care one pipe
id|name| 
id|name| 
id|name| 
id|name| 
name|things that I don't care missing first column and pipe
|name| 

Upvotes: 20

OscarRyz
OscarRyz

Reputation: 199324

I would do something like:

%s/\(.*|.*|\).*/\1

Yeap, that worked:

yeap

Upvotes: 0

Related Questions