user3646369
user3646369

Reputation: 101

Vim replace all characters up to first comma

I am trying to use VIM to replace all the characters up to the first comma in a large text file (10mb+)

I have something that looks like:

foo,bar,sun
apple,pear,goose
monkey,pig,baby

and I want it to look like:

bar,sun
pear,goose
pig,baby

Upvotes: 9

Views: 7541

Answers (4)

teambob
teambob

Reputation: 2084

The following should do it

:%s/^[^,]*,//

Explanation:

  • : Command mode
  • % Apply to every line
  • s Substitute
  • / match
    • ^ From the start of the line
    • [^,] Any character other than comma
    • * (See previous) Repeated or empty
    • , A comma
  • / replace
    • nothing
  • / finished

Alternatively you can use sed:

sed 's/^[^,]*,//' -i FILENAME

or

sed 's/^[^,]*,//' FILENAME > NEWFILENAME

Edit: minor formatting and explain ":"

Upvotes: 19

Eric Mathison
Eric Mathison

Reputation: 1256

:%s/.\{-},//

This version uses a non-greedy quantifier \{-} which causes the preceding dot to be matched 0 or more times but as few as possible (hence it is non-greedy).

This is similar to using a *? in most other regular expression flavors.

Upvotes: 2

FDinoff
FDinoff

Reputation: 31429

You can use

:%norm df,

to run the normal command df, on every line in the file. Which deletes from the beginning of the line up to and including the first comma.

Read :help :normal

Upvotes: 8

xbug
xbug

Reputation: 1472

This should do it:

[esc]:%s:^[^,]*,::

edit: of course you can also use cut:

cut -d , -f 2- < mybigfile.txt > newfile.txt

Upvotes: 2

Related Questions