bashscriptingnewlinetr

Removing a newline character at the end of a file


To remove all newlines you could, say:

tr -d '\n' < days.txt
cat days.txt | tr -d '\n'

but how would you use tr to remove just the newline at the end/bottom of a text file?

I'm not sure to specify just the last one.


Solution

  • 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 foo
    746573740a
    
    # and `stat` tells us the size of the file: 5 bytes (one for each character)
    $ stat -c '%s' foo
    5
    
    # 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 foo
    74657374
    $ cat foo
    test$ 
    

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

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