Can't remove spaces with sed when calling it from sh -c

The following command works

 echo "some text with spaces" | sh -c 'sed -e 's/t//g''

But this doesn't and should

 echo "some text with spaces" | sh -c 'sed -e 's/ //g''

Any ideas?

Try

echo "some text with spaces" | sh -c 'sed -e "s/ //g"'

and/or

echo "some text with spaces" | sh -c 'sed -e 's/[[:blank:]]//g''

and/or

echo "some text with spaces" | sh -c "sed -e 's/ //g'"

But why not directly

echo "some text with spaces" | sed -e 's/ //g'
1 Like

A bit of background: sh -c expects a single string, which is interpreted as a command. Anything after that are positional parameters to that command. So by this way of quoting, sh -c gets passed two strings:

'sed -e 's/

and

//g''

The first is interpreted as a command:

sed -e s/

which is a call to sed with an unterminated substitute pattern s/ (s command) and therefore this will fail.

In the first case, instead of a space there is the letter t , so only one string gets passed to sh -c , namely:

'sed -e 's/t//g''

which gets interpreted as the following command:

sed -e s/t//g

which is a valid command.

1 Like

If you really would need a ' within a ' ' string then you need to end the string with ' then follow an escaped ' then another ' to begin a second string.

echo "some text with spaces" | sh -c 'sed -e '\''s/ //g'\'
1 Like