Remove the newline character from a text file
I had a text file that contained only one line. For some reason I wanted to remove the trailing newline character (‘
\n‘). However, it’s not that easy :) Most text editors automatically add a newline after every line. This is a normal behaviour actually, every line should end with a newline character. But if you want to get rid of it, how to do that?
You can remove the trailing newline with a hex editor. In the Ubuntu repositories I found
hex (from package ‘hex‘) and
ghex2 (from package ‘ghex‘). The first one,
hex, is very simple, it just prints out the contents of a file, similarly to
cat. It is good to identify the newline character. To edit the file, you can use the latter,
Update (20140601): another hex editor is called “
hexedit“. To use it, install it from the package with the same name.
To test your favourite text editor, create a simple file that contains the word “test”, without quotes (i.e. 4 characters). Do not press ENTER at the end. Save it and check its size. If it’s larger than 4 bytes, then the newline character was added automatically. With the command
hex you can verify it.
If you need a hex editor for Windows, try HxD. It’s a freeware hex editor and disk editor.