如何在特定模式后的换行符之间使用sed或awk提取?

我喜欢检查是否还有其他替代方法可以使用其他 bash 命令打印以获取 #Hiko 下的 IP 范围,而不是下面的 sed、tail 和 head,我实际上想出了从我的主机文件中获取所需内容的方法。我只是好奇并热衷于学习更多关于 bash 的知识,希望我能从社区中获得更多知识。:D

$ sed -n '/#Hiko/,/#Pico/p' /etc/hosts | tail -n +3 | head -n -2

/etc/hosts

#Tito

192.168.1.21
192.168.1.119

#Hiko

192.168.1.243
192.168.1.125
192.168.1.94
192.168.1.24
192.168.1.242

#Pico

192.168.1.23
192.168.1.93
192.168.1.121

回答

第一个解决方案:使用显示的示例,您可以尝试以下操作。用 GNU 编写和测试awk

awk -v RS= '/#Pico/{exit} /#Hiko/{found=1;next} found' Input_file

解释:

awk -v RS= '       ##Starting awk program from here.
/#Pico/{           ##Checking condition if line has #Pico then do following.
  exit             ##exiting from program.
}
/#Hiko/{           ##Checking condition if line has #Hiko is present in line.
  found=1          ##Setting found to 1 here.
  next             ##next will skip all further statements from here.
}
found              ##Checking condition if found is SET then print the line.
' Input_file       ##mentioning Input_file name here.

第二种解决方案:不使用RS功能尝试以下。

awk '/#Pico/{exit} /#Hiko/{found=1;next} NF && found' Input_file

第三种解决方案:您可以查找记录#Hiko,然后可以打印其下一条记录并提供显示的样本。

awk -v RS= '/#Hiko/{found=1;next} found{print;exit}' Input_file

注:上述检查这些所有的解决方案,如果字符串#Hiko#Pico存在于任何地方行,如果你想看看精确的字符串,然后只更改上面/#Hiko//#Pico/部分/^#Hiko$//^#Pico$/分别。


回答

使用sed(使用 进行检查GNU sed,其他实现的语法可能会有所不同)

$ sed -n '/#Hiko/{n; :a n; /^$/q; p; ba}' /etc/hosts
192.168.1.243
192.168.1.125
192.168.1.94
192.168.1.24
192.168.1.242
  • -n 关闭模式空间的自动打印
  • /#Hiko/ 如果行包含 #Hiko
    • n 获取下一行(假设总是有一个空行)
    • :a 标签 a
    • n获取下一行(使用n将覆盖模式空间中的任何先前内容,因此在这种情况下仅存在单行内容)
    • /^$/q 如果当前行为空,则退出
    • p 打印当前行
    • ba 分支到标签 a

以上是如何在特定模式后的换行符之间使用sed或awk提取?的全部内容。
THE END
分享
二维码
< <上一篇
下一篇>>