sedbinarytransforminlinerepresentation

sed to find and transform binary number representation


I have a file with binary numbers that I would like to alter inline with sed -i.

The file has lines like this:

  00018342 0000           dc.b   11010101b

So I would like to have it represented this way:

  00018342 0000           dc.b   %11010101

I tried this:

sed -e 's/[[:digit:]]\+\b/%&/g' test.txt

I thought that would only prepend a '%' if it found actual digits preceded by a 'b'. But instead it output this:

  %00018342 %0000           dc.b    11010101b

Any ideas what I am doing wrong? And how would I delete the 'b' after the '%' is prepended?


Solution

  • You can use

    sed 's/\b\([01]\+\)b\b/%\1/g' file
    

    See the online sed demo:

    #!/bin/bash
    s='  00018342 0000           dc.b   11010101b'
    sed 's/\b\([01]\+\)b\b/%\1/g' <<< "$s"
    # =>   00018342 0000           dc.b   %11010101
    

    Details:

    A POSIX ERE version is sed -E 's/\b([01]+)b\b/%\1/g' file.