Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What Vim command to use to delete all text after a certain character on every line of a file?

Scenario:

  • I have a text file that has pipe (as in the | character) delimited data.
  • Each field of data in the pipe delimited fields can be of variable length, so counting characters won't work (or using some sort of substring function... if that even exists in Vim).

Is it possible, using Vim to delete all data from the second pipe to the end of the line for the entire file? There are approx 150,000 lines, so doing this manually would only be appealing to a masochist...

For example, change the following lines from:

1111|random sized text 12345|more random data la la la|1111|abcde
2222|random sized text abcdefghijk|la la la la|2222|defgh
3333|random sized text|more random data|33333|ijklmnop

to:

1111|random sized text 12345
2222|random sized text abcdefghijk
3333|random sized text

I'm sure this can be done somehow... I hope.

UPDATE: I should have mentioned that I'm running this on Windows XP, so I don't have access to some of the mentioned *nix commands (cut is not recognized on Windows).

like image 841
Jason Down Avatar asked Jan 15 '09 20:01

Jason Down


People also ask

How do you select and delete text in Vim?

Using the Shift + V Keys. We can select and delete specific texts using the Shift + V keys and then using the dd command.

How do I delete specific words in Vi?

To delete a word, position the cursor at the beginning of the word and type dw . The word and the space it occupied are removed. To delete part of a word, position the cursor on the word to the right of the part to be saved. Type dw to delete the rest of the word.

What is the command to clear all text?

Place the text cursor at the beginning of the line of text. On your keyboard, press and hold the left or right Shift key and then press the End key to highlight the entire line. Press the Delete key to delete the line of text.


1 Answers

:%s/^\v([^|]+\|[^|]+)\|.*$/\1/
like image 168
Brian Carper Avatar answered Oct 21 '22 00:10

Brian Carper