Replace newline with nul

newlinesosxtext processing

bash, osx mavericks

I want to replace the LF character (hex=0A) with NUL (hex=00) in a txt file. can I use grep or tr or something to accomplish this? I've been using bbedit to replace them, but I'd like something I can do quickly in bash.

Best Answer

Yes, that's a job for tr:

tr '\n' '\0' < file > file.new

Or in-place:

tr '\n' '\0' < file 1<> file

Here, the file is written over itself. That works because we're always writing as much data as we're reading (and not overwriting data we've not read yet). If the tr process is interrupted, it can be started again to finish the job.

Contrary to perl -pi 's/\n/\0/', that preserves all attributes of the file and doesn't break hardlinks or symlinks and doesn't need to duplicate the data on-disk (unless there's some copy-on-write going on underneath).

Related Question