简体   繁体   English

sed:选择要删除的显示行

[英]sed: display lines selected for deleting

How to use verbose flag in sed. 如何在sed中使用详细标志。 Eg. 例如。 If I'm deleting some lines using sed command then I want them to get displayed on a screen whichever lines are getting deleted. 如果我使用sed命令删除某些行,那么我希望它们在屏幕上显示哪个行被删除。 Also let me know if this can be done through a script? 如果可以通过脚本完成,请告诉我?

Thanks in advance 提前致谢

sed doesn't have a verbose flag. sed没有冗长的标志。

You can write a sed script that separates deleted lines from other lines, though. 但是,您可以编写一个sed脚本,将已删除的行与其他行分开。 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. 我想从test.dat中删除以数字开头的每一行。

$ 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. 这是将“执行”删除的sed脚本。 It looks for lines that start with a number, writes them to the file "deleted.dat", and then deletes them from the pattern space. 它查找以数字开头的行,将它们写入文件“deleted.dat”,然后从模式空间中删除它们。

$ 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". 这是它写给“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). 当您确信脚本要做正确的事情时,将输出重定向到另一个文件,或者就地编辑文件( -i选项)。

This might work for you (GNU sed); 这可能适合你(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. 没有详细标记,但通过将要删除的行发送到stderr,可以实现所需的效果。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM