sans-clue has asked for the wisdom of the Perl Monks concerning the following question:

In a file in vi I have text text^@^@^@

I am not sure if these ^@ appear only at the end of the line
In vi hex mode these appear as 0000.

I have tried s/\x0//g s/\x00//g s/\x{0000}//g s/\x0+$//g s/[^:print]//g;

and the result has been that it deletes everything in the line, expect the last one which leaves the text and the nulls in. I just want to remove them. Using Any ideas ?

Replies are listed 'Best First'.
Re: striping nulls
by graff (Chancellor) on Oct 01, 2010 at 00:57 UTC
    Please read instructions when posting -- they say "Put <code> </code> tags around your code and data!" (emphasis in the original text). Note that you can also use <c> and </c>, even within a paragraph.

    Here's a demonstration to show how a regex substitution should work to remove null bytes:

    s/\x00+//g;
    You can also use the "tr///" operator:
    tr/\x00//d; # a.k.a. "y///" : y/\x00//d;
    To see that in action, consider the following command lines, using perl one-liners (and assuming you have the "xxd" utility for doing a hex dump of stdin -- or some equivalent tool):
    perl -e 'print "foo\x00bar" | xxd -g 1 # produces this output (note the null byte): 0000000: 66 6f 6f 00 62 61 72 foo.bar perl -e 'print "foo\x00bar" | perl -pe 's/\x00+//g' | xxd -g 1 # produces this output (no null byte): 0000000: 66 6f 6f 62 61 72 foobar
    If you think you really are doing something like that, and it's not working for you, then you'll have to show a working demonstration of the code that proves it doesn't work.

    My guess is you're doing something else wrong elsewhere in your code, unrelated to the regex. (If your program doesn't use strict; then it might be something as simple as a spelling error in a variable name.)

      I am using strict

      s/\x00+//g;

      simply erases everything, however

      tr/\x00//d;

      works perfectly. Thanks

        If graff's suggestion of s/\x00+//g; "erases everything" in a file that appears to contain both text and nulls, I suspect you don't have what ( it looks like | you said | you think ) you have in the initial data.

        Rather than looking at the data with an editor, check it with an ap designed to read hex... or write one of your own -- a task to which Perl is well suited.

        They both do the same thing.