tags:

views:

47

answers:

3

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.

+2  A: 
my $str = '';

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

print "$str\n";
Alex Howansky
@Alex - thank you! works great.
jda6one9
@Alex - can you tell me what the `.=` is doing?
jda6one9
"$a .= $b" is shortcut notation for "$a = $a . $b" -- i.e., append $b to the end of whatever is already in $a.
Alex Howansky
+3  A: 

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
ghostdog74
Here's one more way: `perl -ne'chomp; s/^([^:]+:)/^a$1^b/; print }{ print "\n"' file`
J.F. Sebastian
Thanks guys! So many ways to do this.
jda6one9
+2  A: 

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.

mscha
I like this one too.
jda6one9