Home > Blockchain >  Remove/Add Comment from config file using sed
Remove/Add Comment from config file using sed

Time:01-21

I have a file which contains below data.

192.168.1.1
255.255.255.0
192.168.1.10

192.168.1.2
255.255.255.0
192.168.1.10

#192.168.2.1
#255.255.255.0
#192.168.2.10

#192.168.2.2
#255.255.255.0
#192.168.2.10

Now I want to achieve following

  1. Remove the # from the beginning of lines which already have it.
  2. Put the # in the beginning of the lines which doesn't have it.

The the final file will look like

#192.168.1.1
#255.255.255.0
#192.168.1.10

#192.168.1.2
#255.255.255.0
#192.168.1.10

192.168.2.1
255.255.255.0
192.168.2.10

192.168.2.2
255.255.255.0
192.168.2.10

I was trying to achieve this with sed using below command in my script but it is not working.

for commenting

sed -i -e "/192.168.1./{N;N;p;}/s/^#*/#/"

for removing comment

sed -i -e "/192.168.2./{N;N;p;}/s/^#*//"

but sed throws error below.

sed: -e expression #1, char 21: extra characters after command

Any suggestion.

CodePudding user response:

Something like this would work:

sed '/^#/{s/^#//;b};s/^./#/' infile

more readable:

sed '
    /^#/ {       # If a line starts with "#"
        s/^#//   # Remove the leading "#"
        b        # Move to next line
    }
    s/^./#/      # If the line is not empty, prepend "#"
' infile

CodePudding user response:

not sure what's the error in your expressions, but a trick that comes to mind is this:

  1. add a # to all lines (so commented lines will start with ##)
  2. remove all ##s.

i.e., if you have a loop in your bash script, you can do something like:


for line in $(cat myfile.txt); do
    echo "#$line" | sed -E 's|^(##)?(.*)|\2|'
done
  •  Tags:  
  • Related