As a stream editor, sed
is more efficient since it doesn’t load the entire file into memory, making it faster than the Vim command. Nonetheless, the difference is negligible for small files.
Using Vim
You can use the :v
command or the %g!
command to delete lines that don’t match a specific pattern. Both commands are equivalent.
Using :v
:v
- Operate on lines not matching the pattern./pattern/
- The regular expression pattern to search for.d
- Delete the lines that meet the criteria.
Using %g!
%
- Operate on the entire file. (this is optional, as it’s the default behavior)g!
- Operate on lines not matching the pattern (equivalent to:v
)./pattern/
- The regular expression pattern to search for.d
- Delete the lines that meet the criteria.
Using Sed
In sed
, you can use the following command to delete lines that don’t match a specific pattern:
/pattern/
- The regular expression pattern to search for.!
- Negate the following command for lines that match the pattern.d
- Delete the lines that meet the criteria.input_file
- The file you want to process.>
- Redirect the output to a new file.output_file
- The file where you want to save the result.