SED uncomment line - How to uncomment a line or all lines with SED
Sed is a very powerful linux command line tool. It is able to replace either static characters or based on regular expressions.
I will give here a few examples on how to uncomment all lines or specific line based on regular expression.
Sed uncomment all lines in a file:Code:
user@linux:~# cat file.conf
line1
#line2
line3A
#setnence abc
sentence def
#sentence bcd
user@linux:~# sed 's/^#\(.*\)/\1/g' file.conf
line1
line2
line3A
setnence abc
sentence def
sentence bcd
Sed uncomment specific line:Code:
user@linux:~# cat file.conf
line1
#line2
line3A
#setnence abc
sentence def
#sentence bcd
user@linux:~# sed 's/^#line2/line2/g' file.conf
line1
line2
line3A
#setnence abc
sentence def
#sentence bcd
Sed uncomment specific lines based on regular expression - uncomment lines containing bc combination:Code:
user@linux:~# cat file.conf
line1
#line2
line3A
#setnence abc
sentence def
#sentence bcd
user@linux:~# sed 's/^#\(.*\)bc\(.*\)/\1bc\2/g' file.conf
line1
#line2
line3A
setnence abc
sentence def
sentence bcd
All the above examples operate on a memory copy of the file, not on the file on the disk. Use "-i" switch of sed to uncomment lines in the file.
Quote:
-i[SUFFIX], --in-place[=SUFFIX]
edit files in place (makes backup if extension supplied)
Code:
user@linux:~# cat file.conf
line1
#line2
line3A
#setnence abc
sentence def
#sentence bcd
user@linux:~# sed -i 's/^#\(.*\)bc\(.*\)/\1bc\2/g' file.conf
user@linux:~# cat file.conf
line1
#line2
line3A
setnence abc
sentence def
sentence bcd
More on sed replacement based on regular expressions:- \(.*\) represents a regular expression matching group for any characters zero or multiple times.
- \1 and \2 represent the first and second regex matching groups in the match criteria. They are used in the replacement part of sed command.