如何在Linux中读取文件并获取特定行 [英] How to read a file and get certain lines in Linux

查看:58
本文介绍了如何在Linux中读取文件并获取特定行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个文件,它的内容是这样的:

I have a file and it has content like this:


abc.com.        IN A            10.10.40.94 ;10.120.40.61    ;10.60.3.135
def.com.            IN CNAME        some-domain.com.

xyz.com.        IN A            10.123.40.32    ;10.145.40.133    ;1.240.3.215
one.com.                IN CNAME        some-other-domain.com.

我想做的是,用IN A获取所有行并将其打印到另一个文件中,以便最终文件如下所示:

What I want to do is, get all the lines with IN A and print them to another file so the final file would look like below:

我尝试了awk,如下所示:

cat dev-mytaxi.com.zone | awk '{print $3}'

但是我如何写文件以及下面提到的最终结果?

but how can I write to a file and the final outcome as mentioned below?

写入新文件的最终输出应类似于:

final output written to a new file should look like:

abc.com 10.10.40.94 10.120.40.61 10.60.3.135
xyz.com 10.123.40.32 10.145.40.133 1.240.3.215

推荐答案

您可以使用自定义FS尝试更简单的awk:

You may try this simpler awk with custom FS:

awk -F '[.[:blank:]]+IN A[[:blank:]]+' 'NF > 1 {
gsub(/[;[:blank:]]+/, " ", $2); print $1, $2}' file

abc.com 10.10.40.94 10.120.40.61 10.60.3.135
xyz.com 10.123.40.32 10.145.40.133 1.240.3.215

工作方式:

  • 在这里,我们使用正则表达式[.[:blank:]]+IN A[[:blank:]]+作为输入字段分隔符,该记录将每条记录都用IN A文本分隔,两边都用空格包围.
  • NF > 1仅对具有IN A记录的行为真
  • gsub转换多个空格,;转换IP地址之间的单个空格
  • Here we are using a regex [.[:blank:]]+IN A[[:blank:]]+ as input field separator that splits each record by a IN A text surrounded by whitespaces on either side.
  • NF > 1 will be true only for lines with IN A record
  • gsub converts multiple spaces and ; with a single space between ip addresses

这篇关于如何在Linux中读取文件并获取特定行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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