Expanding paths in Bash variables into sed expressions
7,661
The problem is that the paths contain / characters, and that character you used in sed as well for the substitution arguments separation. The simplest solution is to just use another separator in sed, one does not appear in your data (say a |, or, as in my subsequent example, a comma):
sed -i "s,${PWD},a Hello World," historia.txt
Edit: Above explains the problem you have (the conflicting slashes). But I see (now) that you are not substituting but adding a line after the matching line. In this case you could escape the slashes in the PWD path for sed, e.g. by:
sed -i "/${PWD//\//\\/}/a Hello World" historia.txt
Related videos on Youtube
Author by
applenic
Updated on September 18, 2022Comments
-
applenic 4 months
I would like to ask what's wrong with this line?
sed -i "/$PWD/a\ Hello World" historia.txtwhen I had it in this
''except for""it was working, of course without expanded variable. -
smw almost 8 yearsYou should be able to use alternate address delimiters for commands other than the
scommand: however they need to be introduced with a backslash e.g."\,$PWD,a\ Hello World" -
Janis almost 8 yearsGood to know. - Now I just wonder about the added leading space; could it be that he wants the data added to the matching line? In this case he'd needsed -i "\,${PWD},s,$, Hello World," historia.txt. -
smw almost 8 yearsIf the OP doesn't want the leading space, then just
"\,$PWD,a\Hello World"should do it -
Janis almost 8 yearsSure. In my previous comment I meant that the single space could be an indicator for a different requirement (append to matching line vs. append a new line after matching line). - But meanwhile the question is accepted, so everything seems to be fine anyway. -
Stéphane Chazelas almost 8 yearsNote that/may not be the only character than needs escaping. All the regular expression operators would as well. Usingawk '1;index($0, ENVIRON["PWD"]){print "Hello World"}'instead (orawk '1;$0 == ENVIRON["PWD"]{print "Hello World"}if you want to match the full line instead of a substring) may be better.