Home > OS >  Comment out all lines that do not start with #
Comment out all lines that do not start with #

Time:01-18

The main goal of this activity is to get all the lines that are not commented at the beginning of each line and then comment them. I need both, first know them and then change them.

I have the below testfile:

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

On my current task first I'm trying to get the lines that are not commented, doing a simple grep:

grep -vi '^#' testfile

that gives me the expected output:

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

Now I'm trying to apply sed to add a # at the beginning of the line, but is not working[one line shell execution as example, this should be on a script]:

NOTE: I can't just add a # to each line every time I run the script. That's why I try to only add to where it doesn't start with the # and match the pattern I get from the grep. –

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

And is does nothing.

Wanting to find the error try this if I try the same with an echo it apply line breaks in each space.

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

Gives:

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

That is not what I expected.

I have tested each part alone and it works, but when I try to integrate them it doesn't work.

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

At this point I am out of ideas. If I think of something better I will post it without a doubt. In the meantime, I'd like some guidance on how to accomplish this task.

Thanks in advance.

CodePudding user response:

Use a pattern that matches lines that start with something other than a comment, and insert # at the beginning.

sed -i '/^[^#]/s/^/#/' testfile

CodePudding user response:

Using awk, add a # to the beginning of lines that do not start with a #:

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