1

I have a data.txt file, the data format is something like this:

a|Êó•
a|Êõ∞
a|Ôõ∏
a|Ôùã
aa|Êòå
aa|Êòç
aaa|Êô∂
aamh|Êöò

all I would like to do is convert the following text into this result:

'a' => ['Êó•','Êõ∞','Ôõ∏','Ôùã'],
'aa' => ['Êòå','Êòç'],
'aaa' => ['Êô∂'],
'aamh' => ['Êöò']

any ideas on that? Thank you.

  • vim is not the right tool for this. You need to use awk, or a shell scrip, (or perl, ruby..) (assuming linux) – Nifle Jul 9 '11 at 9:07
4

A perl solution

#!/usr/bin/perl

use strict;
use warnings;

my $key = 'a';
my @data = ();

while(<>) {  
    chomp($_);
    my $line = $_;

    my ($k, $d) = split(/\|/, $line);

    if($k eq $key) {
        push(@data, $d);
    } else {
        my $text = join ',', map { qq/'$_'/ } @data;
        print "'$key' => [$text],\n";
        @data = ();
        push(@data, $d);
        $key = $k
    }
}
# this prints out any data still left
my $text = join ',', map { qq/'$_'/ } @data;
print "'$key' => [$text],\n"; 
0

viml can be the right tool for the job: sometimes (e.g. Ms Windows) it's easier to install vim than a complete perl/*nix box.

" Parse the lines
let dict = {}
let lines=getline(1,'$')
call filter(lines, 'v:val =~  ".*|.*"')
for l in lines
  let [k,v] = split(l, '|')
  if has_key(dict, k)
    let dict[k] += [v]
  else
    let dict[k] = [v]
  endif
endfor
" produce the new lines ...
" ...in a new buffer
vnew
let res = []
for [k,ll] in items(dict)
  let l = string(k) . ' => ' . string(ll)
  let res += [l]
endfor
let sres=join(res,",\n")
put=sres

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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