使用 sed 删除一段文本直到第一个空行 [英] Delete a block of text until the first blank line using sed

查看:60
本文介绍了使用 sed 删除一段文本直到第一个空行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在发布这个问题之前,我尝试了很多,但正则表达式超出了我的能力并且我失败了几次,我无法通过 Google 或 Stack Overflow 找到我需要搜索的内容.

这是我的示例文件:

主机 xmpp2主机名 172.18.0.42用户根端口 22主机测试主机名 172.18.201.2用户根端口 2223IdentityFile/Users/arash/idkey.pem东道主主机名 79.175.169.10用户根端口 22主机 hv1主机名 172.18.0.4用户根端口 22主机 hv2主机名 172.18.0.5用户根端口 22

我想删除例如这个块

主机测试主机名 172.18.201.2用户根端口 2223IdentityFile/Users/arash/idkey.pem

或任何其他块.如果这些文本块中的任何一个使用特定数量的行,这很简单,但现在可能是 4 行或 5 行或更多,所以我需要从 Host 删除到第一个空行,而不是特定数量的行.

解决方案

sed '/^Host test$/,/^$/d' 文件

输出:

<预>主机 xmpp2主机名 172.18.0.42用户根端口 22东道主主机名 79.175.169.10用户根端口 22主机 hv1主机名 172.18.0.4用户根端口 22主机 hv2主机名 172.18.0.5用户根端口 22

如果您想就地"编辑文件,请添加 sed 的选项 -i.

<小时>

请参阅:堆栈溢出正则表达式常见问题

Before posting this question, I try a lot but regex is beyond my abilities and I fail couple of times, and I can't find what I need searching with Google or Stack Overflow.

Here is my sample file:

Host xmpp2
    HostName 172.18.0.42
    User root
    Port 22

Host test
    HostName 172.18.201.2
    User root
    Port 2223
    IdentityFile /Users/arash/idkey.pem

Host afra
    HostName 79.175.169.10
    User root
    Port 22

Host hv1
    HostName 172.18.0.4
    User root
    Port 22

Host hv2
    HostName 172.18.0.5
    User root
    Port 22

I want to delete for example this block

Host test
    HostName 172.18.201.2
    User root
    Port 2223
    IdentityFile /Users/arash/idkey.pem

or any other block. It's very simple if any of these text blocks is using a specific number of lines, but now it may be 4 lines or 5 lines or more so I need to remove from Host to first blank line, not a specific number of lines.

解决方案

sed '/^Host test$/,/^$/d' file

Output:

Host xmpp2
    HostName 172.18.0.42
    User root
    Port 22

Host afra
    HostName 79.175.169.10
    User root
    Port 22

Host hv1
    HostName 172.18.0.4
    User root
    Port 22

Host hv2
    HostName 172.18.0.5
    User root
    Port 22

If you want to edit your file "in place" add sed's option -i.


See: The Stack Overflow Regular Expressions FAQ

这篇关于使用 sed 删除一段文本直到第一个空行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆