Super User is a question and answer site for computer enthusiasts and power users. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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.

share|improve this question
    
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
up vote 4 down vote accepted

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"; 
share|improve this answer

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
share|improve this answer

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .