Find the answer to your Linux question:
Results 1 to 2 of 2
Enjoy an ad free experience by logging in. Not a member yet? Register.
  1. #1

    Smile Merging Selected Lines in a Text File

    I have a giant text file with thousands of line.
    I want to merge selected multiple lines into a single line.
    Lines that begin with a coma will be merged with previous line.
    Lines that begin with other characters will not be merged with previous line.

    Example: from:

    , bbbb
    , ccccc
    , eeee


    aaaa, bbbb, cccc
    dddd, eeee

    How to do this operation? Can I use sed command?
    Thank you.

  2. #2
    Linux Engineer drl's Avatar
    Join Date
    Apr 2006
    Saint Paul, MN, USA / CentOS, Debian, Slackware, {Free, Open, Net}BSD, Solaris
    Hi, xxqq.

    Brute force:
    # @(#) p1       Demonstrate match including newlines.
    use warnings;
    use strict;
    # slurp in entire file.
    # Perl Best Practices, page 213.
    my $file = do { local $/; <> };
    # replace "newline," with ",".
    # PBP, p 235 - 241
    $file =~ s/\n,/,/xmsg;
    print $file;
    Results on your data file:
    ./p1 data1
    aaaaa, bbbb, ccccc
    dddd, eeee
    Drawback: memory intensive ... cheers, drl
    Welcome - get the most out of the forum by reading forum basics and guidelines: click here.
    90% of questions can be answered by using man pages, Quick Search, Advanced Search, Google search, Wikipedia.
    We look forward to helping you with the challenge of the other 10%.
    ( Mn, 2.6.n, AMD-64 3000+, ASUS A8V Deluxe, 1 GB, SATA + IDE, Matrox G400 AGP )

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts