#!/usr/bin/perl use strict; use warnings; use Data::Dumper; my %hash; while (<>) { # read files from command line (separate by space) e.g. in.txt sample.txt etc... next if /^(\s*(#.*)?)?$/; # skip blank lines and comments chomp; # lines that are not skipped remove new line character '\n' my @tmp = split /:/; # split line on column ':' if (exists $hash{$tmp[0]}) { # check if key exists in hash $hash{$tmp[0]} .= ":".$tmp[2]; # if exists append } else { $hash{$tmp[0]} = $tmp[2]; # if not exists create new element with data } } continue { close ARGV if eof; } print Dumper \%hash; open(my $fh, '>', 'out.txt') # open file to print data or die "Could not open file 'out.txt' $!"; while( my( $key, $value ) = each %hash ){ # iterate over the hash print $fh $key.':'.$value . "\n"; # write data to file } close $fh # close file after finishing or warn "Could not close file 'out.txt' $!"; __END__ $ perl test.pl in.txt $VAR1 = { 'Thailand' => '6', 'China' => '2:2:70', 'Japan' => '6:10' }; $ cat out.txt Thailand:6 China:2:2:70 Japan:6:10