How to un-comment a line in a text file using sed matching a word (Linux command-line)

Here is the code to un-comment a line in a text file that matches a word:

sed -i "/<My-word>/s/^#//g" file-name

We are using sed (sed – stands for stream editor), this works in most Linux / Unix / Debian distributions where you have a bash shell (including Linux or Ubuntu docker containers with bash)

Explanation:

  • -i edit files in place
  • /<My-word>/ the pattern or word you wanted to match
  • /^#/ Pattern you wanted to replace, example: a line starting with a # “^#”
  • // replace it with an empty character (or delete it)
  • file-name the name of your file this operation needs to be done

Demo to uncomment local hosting of codetryout.com, We will just delete the beginning # here.

$ cat /etc/hosts
#127.0.0.1      codetryout.com

Let us uncomment it using sed

$ sed -i "/codetryout/s/^#//g" /etc/hosts

Result:

$ cat /etc/hosts
127.0.0.1       codetryout.com

Another example

We are uncommenting the line containing the word codetryout:

dev@codetryout ~> cat my-file.txt
#Commented line.
Uncommented line.
#Commented line by codetryout.
Another uncommented line.

dev@codetryout ~> sed -i "/codetryout/s/^#//g" my-file.txt
dev@codetryout ~>
dev@codetryout ~> cat my-file.txt
#Commented line.
Uncommented line.
Commented line by codetryout.
Another uncommented line.

dev@codetryout ~>

The same command line syntax works in your shell scripts where you could even use the additional commands, or pipe the output of another command to sed.

Hope it helps to remove comments from the line conditionally, with your Linux scripts or configuration files!