How to convert a csv list (horizontal) from vertical name value pair set
I have a list like this:
GTPYANJ 695848
GTPYANJ 27811
FPORTAL3 432532
I want to turn it into this using regular expressio开发者_C百科ns:
GTPYANJ,695848,27811
FPORTAL3,432532
Suggestions?
load into jEdit (or Notepad++, or some other editor that can search/replace via regex.
Step 1 is to make sure that the delimiter is a tab.
Then, search for
^(.*)\t(.*)\n\1
and replace that with
$1\t$2,
Repeat the find/replace all until no more matches are found.
Perl one-liner:
perl -e 'while(<>) { chomp; ($tag, $num) = split /\s+/; $tmp{$tag} .= ",$num"; } foreach $t (sort keys %tmp) { print $t.$tmp{$t}."\n" } ' myfile.txt
Much easier than trying to hobble together a multi-pass regex that will most likely break a couple of times before you get it right, and which depends on the data being sorted, and which might require a second regex to reformat everything at the end...
精彩评论