Join every two lines of a file

Discussion in 'Perl Misc' started by Ninja Li, Dec 3, 2009.

  1. Ninja Li

    Ninja Li Guest


    I am trying to join every two lines of the following using perl:
    <td align="center" width="50"><nobr>AWR
    <td align="center" width="50"><nobr>ANH
    <td align="center" width="50"><nobr>ACAP

    The output should be as follows:
    <td align="center" width="50"><nobr>AWR</nobr></td>
    <td align="center" width="50"><nobr>ANH</nobr></td>
    <td align="center" width="50"><nobr>ACAP</nobr></td>

    Is there an easy way to join every two lines while at the same time
    remove the " " characters in the line?


    Ninja Li, Dec 3, 2009
    1. Advertisements

  2. Yes. What have you tried so far? Where did it not meet your expectations.
    You're supposed to try first and *then* come here for help.

    But then ... it's pretty simple:

    while (my $line = <$src>) {
    chomp $line;
    $line .= <$src>;
    $line =~ s/ //;
    print $dst $line;
    Josef Moellers, Dec 3, 2009
    1. Advertisements

  3. Pretty trivial. Which part do you have problems with? Designing the
    algorithm? Translating the algorithm into Perl? Debugging the Perl
    program? ...?

    Jürgen Exner, Dec 3, 2009
  4. Ninja Li

    Ninja Li Guest

    I can join the lines by doing the following in awk:

    awk '{ if ( ( NR % 2 ) == 0 ) { printf("%s\n",$0) } else { printf("%s
    ",$0) } }' filename

    I am wondering if there is any one-liner similar to this in perl to
    accomplish it.


    Ninja Li, Dec 3, 2009
  5. perl -lpe'$\ = $. % 2 ? "" : "\n"' filename

    John W. Krahn, Dec 3, 2009
    1. Advertisements

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments (here). After that, you can post your question and our members will help you out.