sed - Commenting a line matching a specific string AND that is not already commented out

*爱你&永不变心* 提交于 2020-11-25 06:19:30

问题


I have the following test file

AAA
BBB
CCC

Using the following sed I can comment out the BBB line.

# sed -e '/BBB/s/^/#/g' -i file

I'd like to only comment out the line if it does not already has a # at the begining.

# sed -e '/^#/! /BBB/s/^/#/g' file

sed: -e expression #1, char 7: unknown command: `/'

Any ideas how I can achieve this?


回答1:


Assuming you don't have any lines with multiple #s this would work:

sed -e '/BBB/ s/^#*/#/' -i file

Note: you don't need /g since you are doing at most one substitution per line.




回答2:


I find this solution to work the best.

sed -i '/![^#]/ s/\(^.*BBB.*$\)/#\ \1/' file

It doesn't matter how many "#" symbols there are, it will never add another one. If the pattern you're searching for does not include a "#" it will add it to the beginning of the line, and it will also add a trailing space.

If you don't want a trailing space

sed -i '/![^#]/ s/\(^.*BBB.*$\)/#\1/' file



回答3:


Another solution with the & special character which references the whole matched portion of the pattern space. It's a bit simpler/cleaner than capturing and referencing a regexp group.

sed -i 's/^[^#]*BBB/#&/' file



回答4:


sed -i '/![^#]/ s/\(^.*BBB.*$\)/#\ \1/' file

This doesn't work for me with the keyword *.sudo, no comments at all...

Ony the syntax below works: sed -e '/sudo/ s/^#*/#/' file




回答5:


Assuming the BBB is at the beginning of a line, I ended up using an even simpler expression:

sed -e '/^BBB/s/^/#/' -i file

One more note for the future me. Do not overlook the -i. Because this won't work: sed -e "..." same_file > same_file.




回答6:


Actually, you don't need the exclamation sign (!) as the caret symbol already negates whatever is inside the square brackets and will ignore all hash symbol from your search. This example worked for me:

sed -i '/[^#]/ s/\(^.*BBB.*$\)/#\ \1/' file




回答7:


I'd usually supply sed with -i.bak to backup the file prior to making changes to the original copy:

sed -i.bak '/BBB/ s/^#*/#/' file

This way when done, I have both file and file.bak and I can decide to delete file.bak only after I'm confident.



来源:https://stackoverflow.com/questions/17998763/sed-commenting-a-line-matching-a-specific-string-and-that-is-not-already-comme

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!