Linux / Unix: sed Command Print Only Matching Lines

In Linux or Unix, you can use the sed command to print only the lines that match a specific pattern. Here’s the basic syntax:

 
sed -n '/pattern/p' file
  • -n – tells sed to not print any lines by default
  • /pattern/ – specifies the pattern to match
  • p – tells sed to print the lines that match the pattern
  • file – the file you want to search

Here’s an example of using sed to print only the lines that contain the word “error” in the file log.txt:

 
sed -n '/error/p' log.txt

This command will print only the lines that contain the word “error” in the log.txt file. If there are multiple lines that match the pattern, they will all be printed.

Leave a Comment