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

Code uncomment a line in a text file that matches a word:

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

We are using sed, this works in most Linux/Unix distributions (including Linux docker containers)

Explanation:

  • -i edit files in place
  • /<My-word>/ the pattern or word you wanted to match
  • /^#/ Pattern you wanted to replace, example: 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

Hope it helps, with your Linux scripts or configuration files!