注释掉所有不以#开头的行

  • 本文关键字:开头 注释 bash shell sed
  • 更新时间 :
  • 英文 :


此活动的主要目标是获取每行开头未注释的所有行,然后对它们进行注释。两者我都需要,先了解它们,然后改变它们。

我有以下testfile:

line1
#comment1
#comment2
wrongcomment#
line2
#comment3
## double comment with space
#
#
# empty space and comment
[ lineinBrackets ]
( lineinBrackets2 )
LinewithValue = 2

在我当前的任务中,我首先尝试获得未注释的行,执行简单的grep:

grep -vi '^#' testfile

给出我期望的输出:

line1
wrongcomment#
line2
# empty space and comment
[ lineinBrackets ]
( lineinBrackets2 )
LinewithValue = 2

现在我试图应用sed在行开头添加一个#,但不工作[一行shell执行为例,这应该是在一个脚本上]:

注意:我不能每次运行脚本时都在每一行添加一个#。这就是为什么我尝试只添加到不以#开头的地方,并匹配我从grep中获得的模式。-

for i in $(grep -vi '^#' testfile); do sed -e '/<pattern>/ s/^#*/#/g' -i testfile;done

它什么也不做。

想要找到错误,试试这个如果我用echo尝试同样的方法,它会在每个空格中应用换行符。

for i in $(grep -vi '^#' testfile); do echo $i;done

给:

line1
wrongcomment#
line2
#
empty
space
[
lineinBrackets
]
(
lineinBrackets2
)
LinewithValue
=
2

那不是我所期望的。

我已经单独测试了每个部分,它工作,但当我试图整合它们时,它不工作。

for i in $(grep -vi '^#' testfile); do sed -e '/$i/ s/^#*/#/g' -i testfile;done

根据请求,我们需要的最终输出是:哪些行需要编辑:

line1
wrongcomment#
line2
# empty space and comment
[ lineinBrackets ]
( lineinBrackets2 )
LinewithValue = 2

与版本相同的文件:

#line1
#comment1
#comment2
#wrongcomment#
#line2
#comment3
## double comment with space
#
#
# # empty space and comment
#[ lineinBrackets ]
#( lineinBrackets2 )
#LinewithValue = 2

我需要能够处理这两个结果。

使用匹配以#开头的行的模式。然后用!否定条件,并在开头替换#

sed -i '/^#/!s/^/#/' testfile

要编辑文件,请使用文件编辑器。

printf '%sn' 'v/^#/s/^/#' 'w' | ed testfile

ed打开命名文件,并对其应用从标准输入读取的命令。

s命令用#替换每行开头的空字符串。v/^#/仅将以下s命令应用于不以#开头的行。w命令将所有挂起的更改写入文件。

当从标准输入中读取所有内容后,编辑器退出。

您可以使用here文档编写相同的命令:

ed testfile <<EOF
v/^#/s/^/#
w
EOF
$ sed -E 's/^#?/#/' file
#line1
#comment1
#comment2
#wrongcomment#
#line2
#comment3
## double comment with space
#
#
# # empty space and comment
#[ lineinBrackets ]
#( lineinBrackets2 )
#LinewithValue = 2

我不知道你为什么需要这个,但是在你的问题中你说你这样做了——下面是如何显示将被上面改变的行:

$ grep -v '^#' file
line1
wrongcomment#
line2
# empty space and comment
[ lineinBrackets ]
( lineinBrackets2 )
LinewithValue = 2

使用awk,在不以#开头的行开头添加#:

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

awk '{print !/^#/ ? "#"$0 : $0}' testfile

awk中这样做是非常不合适的:

gawk   '$_ = __$NF' FS=^# __=#
nawk  '$-_ = __$NF' FS=^# __=#
mawk '$!NF = __$NF' FS=^# __=#
#line1
#comment1
#comment2
#wrongcomment#
#line2
#comment3
## double comment with space
#
#
# # empty space and comment
#[ lineinBrackets ]
#( lineinBrackets2 )
#LinewithValue = 2

最新更新