develooper Front page | perl.beginners | Postings from February 2009

Re: Add Line break when first of a line changes

Thread Previous | Thread Next
February 15, 2009 06:07
Re: Add Line break when first of a line changes
Message ID:
On Sun Feb 15 2009 @  7:25, Jack Butchie wrote:
> I have a txt file of products that I would like to be able to insert a 
> blank line whenever the name of the product changes, to make it easier to 
> read.  I found this srcipt hunting about but I don't know how to apply it 
> to the text file. I've tried all kinds of different things but just don't 
> get it.

Do you already have Perl installed on your computer? If so, you can run it
as follows. Save the Perl script with whatever name you like - say,
new_liner. Then enter this into a terminal:

    perl new_liner filename

Instead of 'filename', enter the name of the file you want to work on. The
two files should be in the same directory for this to work. Otherwise, you
will need to enter the full path of the file, 

    perl new_liner /path/to/filename

You should get output like this: 

    telemachus ~ $ perl new_liner feed 
    LAWN SEED     34.00    RED

    LAWN SEED1    36.00    BLUE
    LAWN SEED1    36.00    BLUE
    LAWN SEED1    36.00    BLUE

    LAWN SEED2    37.00    PINK

Assuming that the output comes out as you want it, you can save it to a new
file with redirection:

    perl new_liner feed_file > new_feed_file

In a nutshell, the script is taking a single filename as an argument,
opening the file and then checking line n for equality with n-1. It will
work with exactly the setup you describe, but it's not a very maintainable
situation (a single extra space or typo will bork the equality test, there's
no way to deal with too many or two few filenames entered on the command
line, etc.).

As a more general rule, I would have to recommend *not* running scripts you
don't understand that you find floating around on the interwebs. 

Hope this helps, T

Thread Previous | Thread Next Perl Programming lists via nntp and http.
Comments to Ask Bjørn Hansen at | Group listing | About