Removing a newline character at the end of a file Removing a newline character at the end of a file bash bash

Removing a newline character at the end of a file


A simpler solution than the accepted one:

truncate -s -1 <<file>>

From the truncate man page (man truncate):

-s, --size=SIZE    set or adjust the file size by SIZESIZE may also be prefixed by one of the following modifying characters:    '+' extend by, '-' reduce by, '<' at most, '>' at least, '/' round down    to multiple of, '%' round up to multiple of.


Take advantage of the fact that a) the newline character is at the end of the file and b) the character is 1 byte large: use the truncate command to shrink the file by one byte:

# a file with the word "test" in it, with a newline at the end (5 characters total)$ cat foo test# a hex dump of foo shows the '\n' at the end (0a)$ xxd -p foo746573740a# and `stat` tells us the size of the file: 5 bytes (one for each character)$ stat -c '%s' foo5# so we can use `truncate` to set the file size to 4 bytes instead$ truncate -s 4 foo# which will remove the newline at the end$ xxd -p foo74657374$ cat footest$ 

You can also roll the sizing and math into a one line command:

truncate -s $(($(stat -c '%s' foo)-1)) foo


If you are sure the last character is a new-line, it is very simple:

head -c -1 days.txt

head -c -N means everything except for the last N bytes