开发者

How to convert a csv list (horizontal) from vertical name value pair set

开发者 https://www.devze.com 2022-12-19 18:56 出处:网络
I have a list like this: GTPYANJ695848 GTPYANJ27811 FPORTAL3432532 I want to turn it into this using regular expressio开发者_C百科ns:

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...

0

精彩评论

暂无评论...
验证码 换一张
取 消