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

标签 awk sed

我想检查是否还有其他替代方法可以使用其他 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$/分别。

关于awk - 如何在特定模式后的换行符之间使用 sed 或 awk 提取?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65610490/

相关文章:

linux - 如何逐行解析df?

awk - 基于公共(public)键在awk中合并3个文件

linux - 使用 awk 或 sed 或 cut 过滤文本文件?

linux - 如何在文件中间写入(Bourne Shell 脚本)

regex - Linux中的SED命令用脚本编辑文件

linux - awk inside shell脚本显示/etc/passwd信息

linux - awk 第一列日期的第二列最大值

awk - 外壳脚本: How to split line?

bash - 删除模式之间的空格

linux - 使用 sed 匹配模式时如何打印最后几行?