连续的行而不更改顺序 [英] consecutive lines without changing order

查看:46
本文介绍了连续的行而不更改顺序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

cat file1
4    
8     
7  

cat file2
4.999286    12.669064   0.000000  
5.999343    12.753258   0.000000  
6.999401    12.654514   0.000000  
7.999458    12.774485   0.000000  
8.999515    12.662147   0.000000  
9.999572    12.700071   0.000000  
10.999629   12.717721   0.000000  

我希望以相同的顺序和另外两个连续的行来grep file1.我试过了:

I am looking to grep file1 with the same order and two more consecutive lines. I tried this:

grep -A 2 -Ff file1 file2

我想要这样的输出:

4.999286    12.669064   0.000000  
5.999343    12.753258   0.000000  
6.999401    12.654514   0.000000  
8.999515    12.662147   0.000000  
9.999572    12.700071   0.000000  
10.999629   12.717721   0.000000  
7.999458    12.774485   0.000000  
8.999515    12.662147   0.000000  
9.999572    12.700071   0.000000 

推荐答案

请尝试以下操作,这将按照与输入文件1中出现$1的顺序相同的顺序给出结果.

Could you please try following, this will give results in same order in which $1 occurs in Input_file1.

awk '
BEGIN{
  s1="\""
}
FNR==NR{
  a[$0]
  next
}
(int($1) in a){
  system("grep -A2 " s1 $0 s1 OFS FILENAME)
}
'  Input_file1  Input_file2



说明: 为上述代码添加说明.



Explanation: Adding explanation for above code.

awk '                                             ##Starting awk program here.
BEGIN{                                            ##Starting BEGIN section of code here.
  s1="\""                                         ##Creating a variable named s1 whose value is "
}                                                 ##Closing BEGIN section of awk code here.
FNR==NR{                                          ##Checking condition if FNR==NR, which will be only TRUE when Input_file1 is being read.
  a[$0]                                           ##Creating an array named a whose index is $0.
  next                                            ##next will skip all further statements from here.
}                                                 ##Closing BLOCK for FNR==NR condition here.
(int($1) in a){                                   ##Checking condition if integer value of $1 is present in array a then do following.
  system("grep -A2 " s1 $0 s1 OFS FILENAME)       ##Using system command to run grep command which will print 2 lines after match of current line in current Input_file name passed to grep by FILENAME variable of awk.
}                                                 ##Closing BLOCK of condition.
'  Input_file1  Input_file2                       ##Mentioning Input_file names here.

输出如下.

4.999286 12.669064 0.000000
5.999343 12.753258 0.000000
6.999401 12.654514 0.000000
7.999458 12.774485 0.000000
8.999515 12.662147 0.000000
9.999572 12.700071 0.000000
8.999515 12.662147 0.000000
9.999572 12.700071 0.000000
10.999629 12.717721 0.000000

这篇关于连续的行而不更改顺序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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