9

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.

2

3 Answers 3

12

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/ //'
2
  • Worth noting that for removing characters, tr -d ' ' also works instead of sed (but is equivalent to sed 's/ //g'). Jun 14, 2016 at 10:40
  • 1
    I basically always put my sed commands in single quotes as a reflex, for roughly this reason. I also tend to use sed -r, for extended regular expressions, which means you don't have to escape your parentheses for capturing groups. Jun 14, 2016 at 16:12
4

You ain't quoting any of your sed expressions, that is the main culprit. put quotes around it like sed ' '. Or Simply you can get that by following tr expression,

tr -d '[:space:]' <<< "312.2 MB"
312.2MB

tr -d ' ' <<< "123.34 KB"
123.34KB

tr -d '[:blank:]' <<< "487.1 GB"
487.1GB

If you are insisting on sed, you can do that by,

sed 's/ //g' 
sed 's/[[:blank:]]//g' 
sed 's/[[:space:]]//g' 
2

use bash:

$ txt="32.2 MB"
$ echo ${txt// /}
32.2MB

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .