sponsor Vim development Vim logo Vim Book Ad

intermediate Tip #1192: Delete everything but the first n fields in a CSV

 tip karma   Rating 1/1, Viewed by 866 

Read and edit this tip on the Vim tip wiki. The wiki may have a more recent version of this tip.

created:   March 31, 2006 14:34      complexity:   intermediate
author:   Ken Holm      as of Vim:   5.7

:%s/^\(\(\([^,]\+\),\)\{n - 1}[^,]\+\).*$/\1/

NOTE: Change the "n - 1" to the number of fields you would like to keep minus 1.

For instance, if you would like to to keep the first 5 fields:


 rate this tip  Life Changing Helpful Unfulfilling 

<< source searching for programmers | Syntax highlighting for HTML with embedded Javascript >>

Additional Notes

walderich@gmx.de, March 31, 2006 16:37
Try this. you don't have to subtract 1 from n
http://bombay11.blogspot.com, April 2, 2006 12:06
Easier to read and customizable, column reformatter:

: %!perl -lne '@x=(split(q/,/));print join(q/,/,@x[ $#x-4 .. $#x  ])'

%            ... means all lines, or you can say 5,10
!perl -lne   ... pipe lines to perl, and print for each line.
@x=split(quoted regexp)  .. split line into array @x.
join( comma, columns to print ).. combine the columns to print.

@x[ $#x-4 .. $#x ] .. columns len(x)-4 to len(x) (last five columns).


: %!perl -lne '@x=(split());print join(q/ /,@x[0,2,5..12])'

Print selected columns, easier to customise and read than regexp ?

j_tech@comcast.net, April 4, 2006 11:35
Just be careful.  Lots of csv data can contain commas in quotes, like names (e.g. "Clauz, Santa").  It doesn't look like those regex handle it.

anon, April 4, 2006 12:45
The splitting of csv file has some pitfalls, see


thanks for pointing this out.
If you have questions or remarks about this site, visit the vimonline development pages. Please use this site responsibly.
Questions about Vim should go to vim@vim.org after searching the archive. Help Bram help Uganda.
Sponsored by Web Concept Group Inc. SourceForge.net Logo