in reply to Way to remove the new line characters at the end of the content in a file

A Perl one-liner to remove the blank lines from your file (changing the original file, please test it first with dummy files):
perl -ni.bak -e "print $_ if /\w/;" my_file.txt
  • Comment on Re: Way to remove the new line characters at the end of the content in a file
  • Download Code

Replies are listed 'Best First'.
Re^2: Way to remove the new line characters at the end of the content in a file
by shmem (Chancellor) on Jul 22, 2015 at 09:48 UTC

    Lines containing e.g. a lone } will be removed with that. I'd do this:

    perl -ni.bak -le "print if $_" my_file.txt

    update: Oops! choroba is right below. Heck...

    perl -ni.bak -le "print if length $_" my_file.txt
    perl -le'print map{pack c,($-++?1:13)+ord}split//,ESEL'
      The last line containing 0 and no newline would be removed :-)
      لսႽ† ᥲᥒ⚪⟊Ⴙᘓᖇ Ꮅᘓᖇ⎱ Ⴙᥲ𝇋ƙᘓᖇ
      Lines containing e.g. a lone } will be removed with that.
      Oops, that's right, but I based the one-liner on the sample data shown by the OP, i.e. a file with a list of server names, which ought to contain some alphanumerical characters (and/or empty lines), not Perl or C code.

      Perhaps a stricter version:

      perl -ni.bak -e "print $_ unless /^[\n\s]+$/;" my_file.txt
      But even this might also fail on some edge cases, the really right regex really depends on the actual content of the file being processed.
Re^2: Way to remove the new line characters at the end of the content in a file
by Anonymous Monk on Jul 24, 2015 at 05:54 UTC
    If there are only blank lines at the end of the file:
    perl -lp00e1 file.txt