当前位置: 动力学知识库 > 问答 > 编程问答 >

perl help to join records and insert characters

问题描述:

Perl newbie here...looking for help to reformat a datafile.

Data looks like this:

num:3460381591

num:1038198413

num:3380733973

I would like to make it one string and then append each start of the rec with ^a and ^b after the colon like this:

^anum:^b3460381591^anum:^b1038198413^anum:^b3380733973

Can someone show me how to do this? Thank you.

网友答案:
my $str = '';

open FILE, "file";
while (<FILE>) {
    chomp;
    my ($k, $v) = split /:/;
    $str .= "^a$k:^b$v";
}
close FILE;

print "$str\n";
网友答案:

If Perl is not a must,

$ awk -F":" '{$1="^a"$1;$2="^b"$2}1' OFS=":" ORS="" file
^anum:^b3460381591^anum:^b1038198413^anum:^b3380733973

else,

perl -F":" -ane 'chomp($F[1]);$F[0]="^a$F[0]";$F[1]="^b$F[1]"; print join ":", @F ' file

Or how about this?

perl -ne 'chomp; s/^/^a/;s/:/:^b/;print' file
网友答案:

An easy way:

#!/usr/bin/perl -p

s/^(\w+):(.*?)\s*$/^a$1:^b$2/;

Or if you want to edit a file in place (and backup the original file in place):

#!/usr/bin/perl -pi.BAK

s/^(\w+):(.*?)\s*$/^a$1:^b$2/;

You can, of course, also run these as one-liners:

perl -p -e 's/^(\w+):(.*?)\s*$/^a$1:^b$2/;' filename
perl -pi.BAK -e 's/^(\w+):(.*?)\s*$/^a$1:^b$2/;' filename

See perldoc perlrun for details.

分享给朋友:
您可能感兴趣的文章:
随机阅读: