5

I have encountered a most annoying problem that occurs on the PWD variable when the current path includes a space. My code looks somewhat like this:

mycommand |sed -E '
 s|mystuff|replacement| ;
 s|'$(pwd)'|replacement| ;
 '

This works great, unless the current path contains a space character. If it does, $(pwd) is expanded to

'mypath/with space'

instead of just

mypath/with space

This cause the sed expression to be messed up (because of the extra quotes):

sed: 1: "s|mypath/with": unterminated substitute pattern

I have noticed that it doesn't help to expand pwd like this: ${PWD//\'/}.

How can this be solved?

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Ludvig A. Norin
  • 5,115
  • 7
  • 30
  • 34

2 Answers2

6

Replace single quotes by double quotes and replace quotes with backquotes around pwd:

mycommand | sed -E "
 s|mystuff|replacement| ;
 s|`pwd`|replacement| ;
"

Double quotes allow expansion of variables and backquoted commands.

mouviciel
  • 66,855
  • 13
  • 106
  • 140
  • 1
    You used a variable where the OP used command substitution, but it works if you change it to match (or if you use it as is in the appropriate situation). – Dennis Williamson Sep 07 '09 at 10:23
  • This will not work, as $(pwd) will be expanded to 'mypath/with space', which won't match in the sed expression. If I used ${PWD//\'/} this would work, though. – Ludvig A. Norin Sep 07 '09 at 10:24
  • @Ludvig: I'm not getting the single quotes when I try this. – Dennis Williamson Sep 07 '09 at 10:29
  • The point about command substitution instead of variable substitution is correct. I update my answer accordingly. – mouviciel Sep 07 '09 at 11:47
  • 1
    To be clear, the solution is to use double-quotes around the sed expression, and to use the PWD environment variable, removing single-quotes, instead of the pwd builtin which will produce single-quotes still: mycommand | sed -E " s|${PWD//\'/}|replacement " – Ludvig A. Norin Sep 07 '09 at 13:58
1

Replace

'$(pwd)'

with

'"$(pwd)"'

It would look like this then:

mycommand | sed -E '  
 s|mystuff|replacement| ;  
 s|'"$(pwd)"'|replacement| ;  
 '
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Atmocreations
  • 9,923
  • 15
  • 67
  • 102