EN VI

sed to find and transform binary number representation?

2024-03-14 23:30:05
How to 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:

  • \b - a word boundary
  • \([01]\+\) - Group 1: one or more 1 or 0 digits
  • b - a b letter
  • \b - a word boundary
  • %\1 - the replacement is a % char + the Group 1 value.

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

Answer

Login


Forgot Your Password?

Create Account


Lost your password? Please enter your email address. You will receive a link to create a new password.

Reset Password

Back to login