How to Use sed to Uncomment Lines Containing Pattern


Often you may want to use sed to uncomment lines in a file that match a specific pattern.

You can use the following syntax to do so:

sed -i '/A00/s/^#//g' employee_info.txt

This particular example will uncomment any lines that are currently commented and contain the pattern A00 in the file named employee_info.txt.

Here is how this syntax works:

  • We use the -i flag to modify the file in-place
  • We first match all lines that contain A00
  • We then use the s command to perform a substitution
  • We specify that the pattern to replace should be the start of the line and the comment symbol ( ^# )
  • We specify that the pattern to use as a replacement is nothing, i.e. the # should simply be deleted
  • We use the g command to specify that this substitution should be made “globally”, i.e. for all occurrences

The following example shows how to use this syntax in practice.

Related: How to Use sed to Comment Out Lines that Match Pattern

Example: Use sed to Uncomment Lines Containing Pattern

Suppose that we have a file named employee_info.txt that contains the ID values for various employees at some company.

We can use the cat command to view the contents of this file:

We can see that some of the employee ID values have been commented out.

Now suppose that we would like to uncomment any line that is currently commented out and contains the pattern A00.

We can use the following syntax to do so:

sed -i '/A00/s/^#//g' employee_info.txt

The following screenshot shows how to use this syntax in practice:

sed uncomment lines containing pattern

Notice that when we use the cat command to view the file again we can see that all lines that were previously commented and contained the pattern A00 have been uncommented.

Related Tutorials

The following tutorials explain how to perform other common tasks in sed:

How to Use sed to Insert Line at Specific Line Number
How to Use sed to Insert Empty Line in a File
How to Use sed to Insert Line with Leading Spaces
How to Use sed to Insert a Line After Match

Leave a Reply