How to read a file and get certain lines in Linux

帅比萌擦擦* 提交于 2021-02-11 07:16:19

问题


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.

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:

I tried awk as follows:

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

回答1:


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

How it works:

  • 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



回答2:


awk '/IN A/ { match($1,/^;/);printf "%s %s ",substr($1,RSTART+RLENGTH),$4;for (i=5;i<=NF;i++) { printf "%s ",substr($i,2) } printf "%s","\n" }' ipdat > ipdat1

Using the above awk command and wit hthe source data in a file called ipdat, we search for the string "IN A" and then process the line accordingly. We take the 1st and 4th delimited field and print with spaces as separators. We then use awk's substr function to take the 5th, 6th and 7th delimited fields, printing from the second character onward in order to strip the first ";" character. All output is redirected to another file (in this case ipdat1)




回答3:


With perl

$ perl -lne 'BEGIN{$,=" "} print /^(\S+?)\.?\s/, /\d+(?:\.\d+){3}/g if /IN A/' ip.txt
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
  • $,=" " sets the separator to be used between multiple arguments/arrays that are passed to print
  • if /IN A/ if input line contains IN A
  • /^(\S+?)\.?\s/ gets the starting non-whitespace characters, ignores a trailing . if present
  • /\d+(?:\.\d+){3}/g this will get all sequences of 4 numbers separated by . character


来源:https://stackoverflow.com/questions/64551925/how-to-read-a-file-and-get-certain-lines-in-linux

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!