4

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.

14

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).

1
  • 7
    It seems slightly dangerous to recommend 1<> here without explaining what it does and why it works in this particular case. – hmakholm left over Monica Mar 30 '18 at 18:07

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.