简体   繁体   English

在文件中尚未以“#”开头的行的第一个字符添加#

[英]Add a # as first character of lines in file that don't already begin with '#'

I am writing a simple shell script that will comment out any lines of code that aren't already commented out. 我正在编写一个简单的shell脚本,它将注释掉尚未注释掉的任何代码行。 I am having trouble determining the correct conditional sed command. 我在确定正确的条件sed命令时遇到麻烦。 The sed command to add a # to any file works but now I need to make it conditional so that I don't end up with two ## on lines that were already commented out. sed命令可以在任何文件中添加#,但是现在我需要使其成为有条件的,这样我才不会在已经注释掉的行上以两个##结尾。

I have been trying different sed commands but am new to Bash and cant figure out the cryptic looking syntax! 我一直在尝试使用不同的sed命令,但对Bash还是陌生的,无法弄清楚它的语法!

sed -i -e "/^#/! 's/^/#/' $file

The first part of the sed command is wrong. sed命令的第一部分是错误的。 I am getting an error, and without the first part of the sed command all lines of the file will have a # added to it even if one already exists on that line. 我遇到了一个错误,如果没有sed命令的第一部分,则该文件的所有行都将添加一个#,即使该行上已经存在该行。 Any help would be greatly appreciated! 任何帮助将不胜感激!

Thanks! 谢谢!

I couldn't find the previous answers to close this as a dup of and no-one else has done it yet so here y'go: 我找不到先前的答案以将其关闭,因为没有其他人完成此操作,所以在这里:

$ cat file
foo
#bar

POSIX: POSIX:

$ sed 's/^/#/; s/^##/#/' file
#foo
#bar

$ sed 's/^#\{0,1\}/#/' file
#foo
#bar

$ sed 's/^\([^#]\|$\)/#\1/' file
#foo
#bar

GNU: GNU:

$ sed 's/^#\?/#/' file
#foo
#bar

There are countless other alternatives... 还有无数其他选择...

awk版本

awk '{print (/^#/?"":"#")$0}' file

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM