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