6

I have a flat file generated from someone else's software. They insert the null character ^@ in certain positions of the file. I wish to replace them with something else like -9. How do I search and replace this character efficiently in terminal on Mac OS X?

Thanks.

There is another post addressing this question in linux.

Community
  • 1
  • 1
user1575175
  • 91
  • 1
  • 1
  • 4

2 Answers2

8

(To maintain a SO tradition of proposing multiple answers with different tools for shell scripting questions):

With tr:

tr -d '\0'
Anton Kovalenko
  • 20,999
  • 2
  • 37
  • 69
  • Do you know the mac osx solution to this? – user1575175 Feb 14 '13 at 18:52
  • 1
    This works fine on osx too. +1 for maintaining SO traditions :) – Anew Feb 14 '13 at 18:54
  • I do not understand. So this will replace all null characters with a space, correct? But what if I wanted another string value? – user1575175 Feb 14 '13 at 18:59
  • `tr -d '\0'` will remove null characters altogether. For replacing with any string you want, take a `sed` solution. For replacing with another *single character*, you can also use something like `tr '\0' '_'`. – Anton Kovalenko Feb 14 '13 at 19:04
  • No, it will delete the character, if you want to replace it with a particular character (say X), you can use `tr '\0' 'X'`, `sed` is better for replacing strings with strings. – Anew Feb 14 '13 at 19:04
  • When processing binary files on macOS, use `LC_ALL=C tr -d '\0'` to avoid `tr: Illegal byte sequence` – that other guy Jun 26 '18 at 21:12
4

With sed:

sed 's/\x0/-9/g' filename > newfile
Anew
  • 5,175
  • 1
  • 24
  • 36
  • Thanks! this actually works well like the other post said. I realized now that I was trying this command on mac osx and that is why I still had issues. I reframed my question. Do you know the answer to this one? – user1575175 Feb 14 '13 at 18:52
  • 4
    Unfortunately on OSX 10.9.4 this is not the case. `printf "\1\0\1" | sed 's/\x0/-9/g' | hexdump` will still yield: `0000000 01 00 01 0a 0000004`. Version information is not in `/usr/bin/sed`, but apparently it's a BSD build from 2005. You can try to install GNU sed instead. – Ray Burgemeestre Dec 03 '14 at 10:44