venciso has asked for the wisdom of the Perl Monks concerning the following question:

Hi guys, I have to files I want to merge. They look as follows

File1: Adam 1 2 3 Eve 4 5 6 File2: Adam 4 5 6 Eve 7 8 9

I want the output file to look like:

Adam 1 2 3 4 5 6 Eve 4 5 6 7 8 9

I know that you can add text to the end of each line of a file by using a command similar to:

perl -p -i.bak -w -e "BEGIN {@ARGV=<file.txt>} s/\z/text to add/g"

But is there a way to do something like the above using text from file2?

I know if you use unix you can use grep or paste or something like that but I want to do this in Windows.

Also, I know a way to do it with a script using hashes but I have a feeling there is a one line command that can do it.

Thanks in advance for your help,

Victor

Replies are listed 'Best First'.
Re: Merging two files by command line
by JavaFan (Canon) on Aug 20, 2009 at 14:23 UTC
    perl -naE 'push @{$%{$F[0]}},@F[1..$#F];END{say"$_ @{$%{$_}}"for keys% +%}' File1 File2
      Thanks JavaFan, I'm a Perl beginner so would it be much trouble if anyone took me through what that line means? Cheers guys, Victor

        You did ask for a one-line script to solve it. That's what a one-line script looks like in Perl: obscure and hard to parse.

        You'd be much better off doing it with multiple lines:

        use strict; use warnings; my %stuff; while (my $line = <>) { chomp $line; my @word = split(q{ }, $line); push (@{$stuff{$word[0]}}, @word[1..$#word]); } for my $key (keys %stuff) { print "$key @{$stuff{$key}}\n"; }

        Example run:

        $ cat file1 Adam 1 2 3 Eve 4 5 6 $ cat file2 Adam 4 5 6 Eve 7 8 9 $ ./merge.pl file1 file2 Adam 1 2 3 4 5 6 Eve 4 5 6 7 8 9
Re: Merging two files by command line
by Fletch (Bishop) on Aug 20, 2009 at 14:54 UTC

    TMTOWTDI, sometimes not even involving perl . . .

    $ for i in file[12] ; { print $i ; cat $i } file1 Adam 1 2 3 Eve 4 5 6 file2 Adam 4 5 6 Eve 7 8 9 $ join -1 1 -2 1 file1 file2 Adam 1 2 3 4 5 6 Eve 4 5 6 7 8 9

    The cake is a lie.
    The cake is a lie.
    The cake is a lie.

      He did say he wanted to do it on Windows, so a response that invokes the Unix command "join" isn't particularly helpful for him.

        ORLY?

        The cake is a lie.
        The cake is a lie.
        The cake is a lie.