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

Hello Monks

We receive some files with \r and no blank line at the end of file...
before the file gets processed we have to remove \r and add new line at the end of file
Is there a one liner that could do this task
I was trying the following but it empties the file

perl -i.bak -ne '(tr/\r//d)' test.dat


Update: I replaced with p but it doesn't add new line at end of file..any help greatly appreciated...
perl -i.bak -pe '(tr/\r//d)' test.dat
Thanks & Regards
Sridhar

Replies are listed 'Best First'.
Re: Adding \n (new line) and removing \r in a file
by davorg (Chancellor) on Sep 21, 2006 at 12:43 UTC

    The -n command line option doesn't print anything to the output file. Try using -p instead.

    Update: And with the end of file processing added:

    perl -i~ -pe 'tr/\r//d; $_ .="\n" if eof' file_name
    --
    <http://dave.org.uk>

    "The first rule of Perl club is you do not talk about Perl club."
    -- Chip Salzenberg

Re: Adding \n (new line) and removing \r in a file
by graff (Chancellor) on Sep 21, 2006 at 13:11 UTC
    Do you mean there is a "\r" at the end of the file and you want "\n" there instead? If so, how about changing "\r" to "\n" if it doesn't already precede "\n", and then deleting any "\r" that remains:
    perl -i.bak -pe 's/\r(?!\n)/\n/g; tr/\r//d' test.dat
    Or, if there is no "\r" at the end -- that is, you're deleting any/all "\r" in the file and adding "\n" at the end, add the "-l" option:
    perl -i.bak -lpe 'tr/\r//d' test.dat
    (but that might not do exactly what you want, depending on what OS you're running on)
Re: Adding \n (new line) and removing \r in a file
by mantra2006 (Hermit) on Sep 21, 2006 at 13:29 UTC
    Thanks to davorg and graff..both oneliners worked..actually
    this one liner has to remove all \r in file and add \n at the
    end of file....somefiles comes with \n at end of file and
    somefiles with no \n...this oneliner should check to see
    if there is any \r and add \n at eof.

    Thanks again
    Thanks & Regards
    Sridhar