Bash quoting of current path (pwd)
Asked Answered
C

2

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?

Chunchung answered 7/9, 2009 at 9:35 Comment(4)
Is that really the command? Variables aren't expanded inside single-quotes, so I can't see how $(pwd) in the above would be getting expanded at all.Platino
Thanks for pointing that out. I've added the missing quotes.Chunchung
Have you tried using the equivalent environment variable ($PWD) instead of command substitution to see if it makes a difference?Amethist
As is explained in the question, yes. The contents of the variable is what is returned by the pwd command (including the single-quotes).Chunchung
D
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.

Diversiform answered 7/9, 2009 at 10:11 Comment(5)
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).Amethist
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.Chunchung
@Ludvig: I'm not getting the single quotes when I try this.Amethist
The point about command substitution instead of variable substitution is correct. I update my answer accordingly.Diversiform
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 "Chunchung
A
1

Replace

'$(pwd)'

with

'"$(pwd)"'

It would look like this then:

mycommand | sed -E '  
 s|mystuff|replacement| ;  
 s|'"$(pwd)"'|replacement| ;  
 '
Apophyge answered 7/9, 2009 at 10:14 Comment(3)
You have a double quote out of place in the line following "with"Amethist
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 replacedPATHPART2Apophyge
No, compare the line I mentioned with the next-to-last line. It's just a typo.Amethist

© 2022 - 2024 — McMap. All rights reserved.