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.
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems. It only takes a minute to sign up.
Sign up to join this communitybash, 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.
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<>
here without explaining what it does and why it works in this particular case.
– hmakholm left over Monica
Mar 30 '18 at 18:07