Andy K
Andy K

Reputation: 5085

how do I change the field delimiter after the nth column

I have a file with thousand of lines like below

32322621661395926569;adverline;www.societe.com_societe;identite;Salarie2;fiche;btp_et_construction;CA4
32322621661395926569;adverline;www.societe.com_societe;identite;Salarie2;fiche;energy;CA4;nunuc_muchemuche

The delimiter is done with ;. I'm trying to change the delimiter after the 4th column. So every semi-colon after identite will be changed to a ,.

I've tried that

awk '$4=$4' FS=";" OFS="," filename 

but it is changing everything to a comma.

if you have any tips, I'm all ears.

Upvotes: 2

Views: 406

Answers (2)

Jason Hu
Jason Hu

Reputation: 6333

this piece of perl code should work.

#!/usr/bin/perl

open FH, $filename; # fill it in
while (<FH>){
    my @elems = split ';', $_;
    push @elems, join ',', splice @elems, 3, @elems - 3;
    print join ';', @elems;
}

Upvotes: 1

Steve
Steve

Reputation: 54592

You can specify the occurrence using sed:

sed 's/;/,/4g' file

Results:

32322621661395926569;adverline;www.societe.com_societe;identite,Salarie2,fiche,btp_et_construction,CA4
32322621661395926569;adverline;www.societe.com_societe;identite,Salarie2,fiche,energy,CA4,nunuc_muchemuche

Upvotes: 7

Related Questions