How to Use sed to Comment Out Lines that Match Pattern


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

You can use the following syntax to do so:

sed 's/^A00/#&/' employees.txt

This particular example will comment out each line that starts with the pattern A00 in the file named employees.txt.

Here is how this syntax works:

  • We use the s command to perform a substitution
  • We specify that the pattern to replace should be the start of the line ( ^ ) followed by A00
  • We specify that the pattern to use as a replacement should be # followed by the pattern that was matched ( & )

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

Example: Use sed to Comment Out Lines that Match Pattern

Suppose that we have a file named employees.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:

Now suppose that we would like to comment out each line in the file that starts with the pattern A00.

We can use the following syntax to do so:

sed 's/^A00/#&/' employees.txt

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

sed comment out lines if match

Notice that each line that contains the pattern A00 in the file has been commented out.

Note that if you would like to save these changes to the file in-place then you can add the -i flag as follows:

sed -i 's/^A00/#&/' employees.txt

This will save the changes to the employees.txt file in-place.

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