Use sed with back references

regular expressionsed

I am trying to remove a space between 2 strings, they are like this:

312.2 MB
123.34 KB
487.1 GB

I want to change them to:

312.2MB
123.34KB
487.1GB

I've been trying and I can get:

echo "312.2 MB" | sed s/[0-9][[:space:]][GMK]//g
312.B

But when I try to do backreferences with sed:

echo "312.2 MB" | sed s/\([0-9]\)[[:space:]]\([GMK]\)/\1/g
312.2 MB

My guess is that there is only one match, and then the back reference is the complete match, but:

echo "312.2 MB" | sed s/\([0-9]\)[[:space:]]\([GMK]\)/TRY/g
312.2 MB

So, it is not working anymore when I use the () to capture the characters

Probably the regex is not completely correct, but I don't know why.

Best Answer

The problem is quoting.

Because you don't quote your sed command, the parenthesis \(...\) was interpreted by the shell before passing to sed.

So sed treated them as literal parenthesis instead of escaped parenthesis, no back-reference affected.

You need:

echo "312.2 MB" | sed 's/\([0-9]\)[[:space:]]\([GMK]\)/\1\2/g'

to make back-reference affected, and get what you want.

Or more simply:

echo "312.2 MB" | sed 's/ //'
Related Question