How can I use the vim editor to format the text like this?

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.

user28167

Posted 2011-07-09T07:32:59.893

Reputation: 481

vim is not the right tool for this. You need to use awk, or a shell scrip, (or perl, ruby..) (assuming linux) – Nifle – 2011-07-09T09:07:36.813

Answers

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"; 

Nifle

Posted 2011-07-09T07:32:59.893

Reputation: 31 337

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

Luc Hermitte

Posted 2011-07-09T07:32:59.893

Reputation: 1 575