Search code examples
textsed

Removing the new line in the last line of a text file using sed


I wanna remove the new line in the last line of my text file using sed. For example the input is like the following:

1
1
1
1
1
1

And I want to have an output like this without any new lines at the end of the text file:

 1
 1
 1
 1
 1
 1

Solution

  • This might work for you (GNU sed):

    sed -z 's/\n\+$//' file
    

    This will remove a newline(s) at the end of a file provided there are no null characters.

    N.B. Normal use of sed i.e. without the -z option which slurps the file into memory, will remove any newlines before the sed commands can act on them.