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

I am old school, I have a DOS batch that copies a file created by another app from one location and drops it in another. The app adds a CR and an LF at the end of the text file. I need to remove the last CR and LF. The file transfer runs every night and the data size will vary. I know Perl could do this but I an to much of a novice with Perl. Can the good monks help me? Mike

Replies are listed 'Best First'.
Re: delete last CR and LF from txt
by roboticus (Chancellor) on Feb 22, 2010 at 18:08 UTC

    mph151:

    Perhaps the simplest way is to:

    1. Open the file
    2. Seek to two byes before the end of the file
    3. Truncate the file
    4. close the file

    Note: the first word of each line is the name of the perl function that does the job.

    ...roboticus

Re: delete last CR and LF from txt
by ikegami (Patriarch) on Feb 22, 2010 at 18:19 UTC
    The following will remove all trailing empty lines.
    perl -i.bak -nle"while ($empty) { --$empty; print '' } if (length()) { + print } else { ++$empty }" filename

    For example,

    foo CR LF bar CR LF CR LF CR LF
    will become
    foo CR LF bar CR LF
Re: delete last CR and LF from txt
by BrowserUk (Patriarch) on Feb 22, 2010 at 19:28 UTC

    If you know the crlf will always be there:

    perl -E"$s=-s $ARGV[ 0 ]; truncate( $ARGV[0], $s-2 ) or die $!" junk.d +at

    Examine what is said, not who speaks -- Silence betokens consent -- Love the truth but pardon error.
    "Science is about questioning the status quo. Questioning authority".
    In the absence of evidence, opinion is indistinguishable from prejudice.
      Even if you dont know its there you can seek to the last 2 bytes and read them and compare them to CR/LF. If they are indeed a CR/LF then truncate, else leave it alone. Its not quite a one-liner but still tiny.
Re: delete last CR and LF from txt
by ww (Archbishop) on Feb 22, 2010 at 18:11 UTC
    see perldoc perlretut and friends.

    You're looking for a regex anchored to the end of the first line when using read, reverse, regex, re-reverse and write.