I have a database containing a list of unsigned longs representing a bunch of memory addresses followed by an offset within two brackets (e.g. Mem[offset], 0x2322AD4[3]), and some other data. What I am trying to achieve is separate the offset from the memory address by replacing the opening bracket with a single space and get rid of the closing bracket. The procedure I'm taking goes as follows:

  1. Find every digit that is followed by an opening bracket (this is because my other data may contain a bracket that should NOT be messed with).
  2. Replace ONLY the bracket with a single space.
  3. Find every digit that is followed by a closing bracket, and ONLY replace the closing bracket with a single space.

The brackets could be easily handled with the following two commands:

sed 's/\[/ /' #replace the opening bracket with a single space.

sed 's/\]//' #delete the closing bracket

But again, I don't want to mess with the other data stored in the database.

My second guess was getting back-referencing involved to handle the job. Is it possible to tell sed to find every digit followed by an opening brace and back-reference the digit and add a space right after it, resulting in something like this:

0x2322AD4 3]

So then I can just go ahead and use the second command mentioned above to get rid of the closing brace?

If there is a whole difference approach to solve the problem, please post.


I think what you're looking for is something like this:

sed -r 's/(0[xX][[:xdigit:]]+)\[([[:digit:]]+)\]/\1 \2/g'


$ sed -r 's/(0[xX][[:xdigit:]]+)\[([[:digit:]]+)\]/\1 \2/g' <<EOF
> mem+offset: 0x2322AD4[3]  0x232BEEF[12]
> unchanged: 0x22343AF word[2] 7E[word]

mem+offset: 0x2322AD4 3  0x232BEEF 12
unchanged: 0x22343AF word[2] 7E[word]

Note: without the 0[xX], it would have considered d[2] to be replaceable in the second input line.

  • That didn't work even though I don't see what's wrong with it.. maybe sed deosn't recognize :digit:?. However, I was able to figure it out before I revisited my question. Thanks though. – Fadi Hanna AL-Kass Jul 29 '13 at 1:18
  • @FadiHannaAL-Kass: Just out of curiosity, what OS are you using? On MacOS/FreeBSD, you probably have to use -E instead of -r; I don't have one of those to try. But the example above is a cut&paste from my terminal (ubuntu 12.04). (It could also potentially be your locale, I suppose.) – rici Jul 29 '13 at 2:13
  • I executed the command on Ubuntu 13.04. I do have an iMac though. I'll execute the command on it, and let know know of the outcome :-) – Fadi Hanna AL-Kass Jul 29 '13 at 2:44

I was able to figure it out. Here's the answer for future visits to the question:

sed -r 's/(0[Xx][A-Fa-f0-9]+)\[([0-9]+)\]/\1 \2/g'

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.