Adding a comment character in the easiest way

I want to search for a file for a specific line and then put a comment at the beginning of that line. But I need an answer that avoids regexes, globals and all the other fancy stuff.

I wrote this line:

sed -i.bak '/PermitRootLogin no/# PermitRootLogin no/' ./sshd_config

      

but I am getting the error:

sed: -e expression # 1, char 21: comments do not accept any addresses

I guess the problem is that I need to escape the # character, but I don't find any resources on how to do this, or even mention it. I've tried different combinations of putting ^ or \ or \ ^ before the #, but I'm wrong.

Note that I am deliberately repeating the text to be replaced. I would like to get the simplest solution to this question: how to replace "XYX" with "# XYZ" in the most obvious way possible.

+3


source to share


1 answer


As @mlt pointed out in the comments, you can try adding s at the beginning of your sed command. Straight from his comment:

s/PermitRootLogin....

      

I see that you said that you are deliberately repeating the test that needs to be replaced. If you mean it, you want it to be the same, perhaps consider grouping your agreed text. I understand that you may have meant that you just want to be typed manually. Anyway, here's how to match the grouped text and add a comment character:



s/(PermitRootLogin)/# \1/ 

      

The paranas indicated that the agreed text should be treated as a group, \ 1 indicates that you want to put a similar group there.

Hope this was helpful. Happy coding! Leave a comment if you have any questions.

+1


source







All Articles