views:

348

answers:

2

Dear lazyweb,

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//\'/}.

Any ideas on how this can be solved?

+1  A: 

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
This will work. Great!
Aviator
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
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
@Ludvig: I'm not getting the single quotes when I try this.
Dennis Williamson
The point about command substitution instead of variable substitution is correct. I update my answer accordingly.
mouviciel
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
+1  A: 

what happens if you replace

'$(pwd)'

with

'"$(pwd)"'

would look like this then:

mycommand | sed -E '  
 s|mystuff|replacement| ;  
 s|'"$(pwd)"'|replacement| ;  
 '
Atmocreations
You have a double quote out of place in the line following "with"
Dennis Williamson
oh well... may i have an old version of sed? i don't even have the option -E, only -e. I've checked using the following command: echo PART1$(pwd)PART2| sed -e 's|PART1|replaced| ; s|'"$(pwd)"'|PATH|;' ;and the output is replacedPATHPART2
Atmocreations
No, compare the line I mentioned with the next-to-last line. It's just a typo.
Dennis Williamson
The typo is fixed.
mouviciel
thanks, haven't seen it though :P
Atmocreations