shell 注解掉所有不以#开头的行

tvokkenx  于 2023-01-21  发布在  Shell
关注(0)|答案(5)|浏览(292)

这个活动的主要目标是在每一行的开头得到所有没有注解的行,然后注解它们,我两者都需要,首先了解它们,然后再修改它们。
我有下面的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

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

hmmo2u0o

hmmo2u0o1#

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

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

new9mtju2#

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

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

ed打开指定的文件,并将从标准输入读取的命令应用于该文件。
s命令用#替换每行开头的空字符串。v/^#/仅将以下s命令应用于 * 不 * 以#开始的行。w命令将所有挂起的更改写入文件。
从标准输入读取所有内容后,编辑器退出。
您可以使用以下文档编写相同的命令:

ed testfile <<EOF
v/^#/s/^/#
w
EOF
icnyk63a

icnyk63a3#

$ 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
h7appiyu

h7appiyu4#

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

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

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

osh3o9ms5#

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

相关问题