[Date Prev][Date Next][Thread Prev][Thread Next] [Search] [Date Index] [Thread Index]

[FWP] joining columns in csv files



Here's a problem that occurred on a list I'm on. Someone has a csv file
with 8 columns and they want to merge colums 4, 5, 6 and 7. So 

1,2,3,4,5,6,7,8,9 => 1,2,3,4567,8,9

there were various shots involving sed, awk and perl. The perl ones
tended to use split and join or just the obvious substitution using lots
of parentheses. Here's what I came up with

The first one only works becuase the fields to be joined are adjacent
but I like it becuase I've never seen this before

perl -pi -e 's/((?:.*?,){3})(.*?),/$1$2/' filename filename filename

the second one was shorter than anything else offered and is kinda
perverse

perl -pe '$i=1;s/,/$i++=~m#4|5|6#?"":","/ge'

it is also quite general, you just replace 4|5|6 with whatever you want,
to eliminate commas in different positions, although you have to anchor
the inner regex if you have too many columns as double digits could mess
things up. IE

perl -pe '$i=1;s/,/$i++=~m#^4|5|6$#?"":","/ge'

which is robust, general, short and fun.

Anyone fancy a go?

Fergal

==== Want to unsubscribe from Fun With Perl?  Well, if you insist...
==== Send email to <fwp-request@technofile.org> with message _body_
====   unsubscribe