9

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
1
  • You say "replace" but you really are deleting characters. Nov 20, 2014 at 7:25

4 Answers 4

18

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 ":"

8

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

2

This should do it:

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

edit: of course you can also use cut:

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

:%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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.