Question

I have a csv file which contains some 1000 fields with values, the headers are something like below:

v1,v2,v3,v4,v5....v1000

I want to extract the last column i.e. v1000 and its values.

I tried %s/,[^,]*$// , but this turns out to be exact opposite of what i expected, Is there any way to invert this expression in VI ?

I know it can be done using awk as awk -F "," '{print $NF}' myfile.csv, but i want to make it happen in VI with regular expression,Please also note that i have VI and don't have VIM and working on UNIX, so i can't do visual mode trick as well.

Many thanks in advance, Any help is much appreciated.

Was it helpful?

Solution

Don't you just want

%s/.*,\s*//

.*, is match everything unto the last comma and the \s* is there to remove whitespace if its there.

OTHER TIPS

You already accepted answer, btw you can still use awk or other nice UNIX tools within VI or VIM. Technique below calls manipulating the contents of a buffer through an external command :!{cmd}

As a demo, let's rearrange the records in CSV file with sort command:

first,last,email
john,smith,john@example.com
jane,doe,jane@example.com

:2,$!sort -t',' -k2

-k2 flag will sort the records by second field.

Extract last column with awk as easy as:

:%!awk -F "," '{print $NF}'

Dont forget cut!

:%!cut -d , -f 6

Where 6 is the number of the last field.

Or if you don't want to count the number of fields:

:%!rev | cut -d , -f 1 | rev
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top