0

This is what I was hoping would work utilizing sed, but no dice so far:

sed '/^command=/ /\/opt\/home\/user/!s@/home/user/@/opt/home/user/@' authorized_keys

Note that the @ is just a funny delimiter I chose for the substitution to more easily view the slashes.

Basically what I want that regex to do is: "On any line in the file starting with the string: command= then if the string: /opt/home/user does not exist, then replace /opt/user with /opt/home/user"

I know I could theoretically do this with if statements, greps, and then sed, but that seems non elegant to me. I am pretty certain sed can do this itself in a one liner regex, but any combination I've tried seems to give me all sorts of syntax errors. Oddly enough, those regex statements used individually don't give any syntax errors when combined with the substitution, only when I try to combine them do I have issues.

Anyone have a more elegant way to do this with sed? Or was I right in assuming that greps, and if statements before the sed are the best way to do this.

  • 1
    Use the same "funny" delimiter for the second condition where regex contains /... Also, AND in sed is { so sed '/^command=/{\@/opt/home/user@!s@/home/user/@/opt/home/user‌​/@}' – don_crissti Sep 21 '16 at 20:26
  • That did it! Thanks Don, also, it's odd that the first @ must be escaped to be utilized as a delimiter, but I suppose that's the way it is. It's helpful to know what AND is defined as. – Viscosity Sep 21 '16 at 20:30
  • You can use any char in as a delimiter in a context address as long as you escape it see this Q – don_crissti Sep 21 '16 at 20:32
  • The comments just above here made by don_crissti explains the answer, and it works perfectly. Thanks don_crissti! – Viscosity Sep 22 '16 at 13:28
2

don_crissti advise an elegant solution in comments but for educational purpose other variant here

sed '/^command=/! b; \@/opt/home/user@! s@/home/user@/opt&@' authorized_keys

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.