With sed, how can I delete a line after a match but keep the match?
- User
With sed, how can I delete a line after a match but keep the match?
- Assistant
You can use the
sedcommand with the option-eto specify the editing commands and the option-nto suppress automatic printing of pattern space.The basic syntax for deleting a line after a match but keeping the match in
sedis:sed -e '/pattern/{N;d;}' file.txtThis command will delete a line that matches the pattern and the next line after it, but keep the line with the pattern.
Here is a breakdown of the command:
/pattern/- this is the pattern to match{}- this is used to group a set of commands to be executed on the matched lineN- this appends the next line to the pattern spaced- this deletes the pattern space (which now contains two lines - the match and the next line)
For example, let's consider a file
file.txtwith the following content:This is line 1 This is line 2 This pattern should be deleted and line 3 should be kept This is line 4To delete the line after the match "pattern" but keep the match, you can run the following command:
sed -e '/pattern/{N;d;}' file.txtThe output would be:
This is line 1 This is line 2 This pattern should be deleted and line 3 should be kept This is line 4 - User
it deleted the match line.
- Assistant
I'm sorry for the confusion. To delete the line after the match but keep the match, you can use the
pcommand to print the pattern space with the match and then use thedcommand to delete the line after the match.Here's the corrected
sedcommand:sed -n '/pattern/{p;n;d;};p' file.txtThis command will print the matched line and delete the next line after the match while preserving all the other lines.
Here is a breakdown of the command:
-noption - suppresses the automatic printing of pattern space/{pattern/}- selects only lines that match the specified pattern{p;n;d;}- executes this command for matching linesp- prints the pattern space, which includes the matched linen- reads the next line into the pattern spaced- deletes the pattern space, which now contains the line after the match
p- prints all other lines
For example, using the same sample file
file.txtwith the pattern "pattern", if you run the following command:sed -n '/pattern/{p;n;d;};p' file.txtThe output will be:
This is line 1 This is line 2 This pattern should be deleted and line 3 should be kept This is line 4I apologize again for any confusion caused by my previous answer.