Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sed: display lines selected for deleting

Tags:

regex

sed

How to use verbose flag in sed? E.g. If I'm deleting some lines using sed command then I want them to get displayed on a screen whichever lines are getting deleted. Also let me know if this can be done through a script?

like image 261
user2439552 Avatar asked Oct 19 '25 13:10

user2439552


2 Answers

sed doesn't have a verbose flag.

You can write a sed script that separates deleted lines from other lines, though. You can look at the deleted lines later, and decide whether deleting them was a good idea.

Here's an example. I want to delete from test.dat every line that starts with a number.

$ cat test.dat
1 First line
2 Second line
3 Third line
A Keep this one

Here's the sed script that will "do" the deleting. It looks for lines that start with a number, writes them to the file "deleted.dat", and then deletes them from the pattern space.

$ cat code/sed/delete-verbose.sed
/^[0-9]/{
w /home/myusername/deleted.dat
d
}

Here's what happens when you run it.

$ sed -f code/sed/delete-verbose.sed test.dat
A Keep this one

And here's what it wrote to "deleted.dat".

$ cat deleted.dat
1 First line
2 Second line
3 Third line

When you're confident the script is going to do the right thing, redirect output to another file, or edit the file in-place (-i option).

like image 127
Mike Sherrill 'Cat Recall' Avatar answered Oct 22 '25 04:10

Mike Sherrill 'Cat Recall'


This might work for you (GNU sed);

sed -e '/pattern_to_delete/{w /dev/stderr' -e ';d}' input_file > output_file

There is no verbose flag but by sending the lines to be deleted to stderr the effect you require can be achieved.

like image 35
potong Avatar answered Oct 22 '25 05:10

potong



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!