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)


  • -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, We will just delete the beginning # here.

$ cat /etc/hosts

Let us uncomment it using sed

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


$ cat /etc/hosts

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