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
Share:
7,661

Related videos on Youtube

Author by

applenic

Updated on September 18, 2022

Comments

  • applenic 4 months

    I would like to ask what's wrong with this line?

    sed -i "/$PWD/a\ Hello World" historia.txt
    

    when I had it in this '' except for "" it was working, of course without expanded variable.

  • smw almost 8 years
    You should be able to use alternate address delimiters for commands other than the s command: however they need to be introduced with a backslash e.g. "\,$PWD,a\ Hello World"
  • Janis
    Janis almost 8 years
    Good 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 need sed -i "\,${PWD},s,$, Hello World," historia.txt.
  • smw almost 8 years
    If the OP doesn't want the leading space, then just "\,$PWD,a\Hello World" should do it
  • Janis
    Janis almost 8 years
    Sure. 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
    Stéphane Chazelas almost 8 years
    Note that / may not be the only character than needs escaping. All the regular expression operators would as well. Using awk '1;index($0, ENVIRON["PWD"]){print "Hello World"}' instead (or awk '1;$0 == ENVIRON["PWD"]{print "Hello World"} if you want to match the full line instead of a substring) may be better.

Related