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.


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
  • 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" – steeldriver Mar 15 '15 at 16:42
  • 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. – Janis Mar 15 '15 at 16:49
  • 1
    If the OP doesn't want the leading space, then just "\,$PWD,a\Hello World" should do it – steeldriver Mar 15 '15 at 16:53
  • 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. – Janis Mar 15 '15 at 17:08
  • 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. – Stéphane Chazelas Mar 16 '15 at 15:50

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.