搜索模式和行的grep部分

时间:2018-10-12 05:52:54

标签: awk

Grep模式并在匹配模式41572:90000:和90002:之后选择行的一部分。

input

hyt : generation
str : 122344
stks : 9000233
dhy : 9000aaaa
sjyt : hist : hhh9000kkk
Count ch : 41572:47149-47999/2(14485-14910) 41584:47149-47999/2(14911-15449) 90000:47919-47999/2(15447-15477) 90002:47919-47999/2(15478-15418) 
drx : 12345

此处使用的代码

awk '
{
  flag=""
  for(i=1;i<=NF;i++){
    if($i ~ /41572/ || $i ~ /90000/ || $i ~ /90002/){
       flag=1
       printf("%s%s",$i,i==NF?ORS:OFS)
    }
  }
}
!flag
'   Input_file

使用RavinderSingh13先生的上面的代码,我得到以下输出

hyt : generation
str : 122344
stks : 9000233
dhy : 9000aaaa
sjyt : hist : hhh9000kkk
41572:47149-47999/2(14485-14910) 90000:47919-47999/2(15447-15477) 90002:47919-47999/2(15478-15418) 
drx : 12345

想要获得以下输出

hyt : generation
str : 122344
stks : 9000233
dhy : 9000aaaa
sjyt : hist : hhh9000kkk
Count ch : 41572:47149-47999/2(14485-14910) 90000:47919-47999/2(15447-15477) 90002:47919-47999/2(15478-15418) 
drx : 12345

预先感谢

1 个答案:

答案 0 :(得分:1)

考虑到您的实际Input_file与所示示例相同,如果是,那么以下内容可能会对您有所帮助。

awk '
{
  flag=flag2=""
  for(i=3;i<=NF;i++){
    if($i ~ /41572/ || $i ~ /90000/ || $i ~ /90002/){
       flag2++
       if(flag2==1){
           printf("%s %s : ",$1,$2)
       }
       flag=1
       printf("%s%s",$i,i==NF?ORS:OFS)
    }
  }
}
!flag
'   Input_file

说明: 在此处也为上述代码添加了说明。

awk '                                                     ##Starting awk script here.
{                                                         ##Starting main block from here when Input_file is being read.
  flag=flag2=""                                           ##Nullifying variables named flag and flag2 here.
  for(i=3;i<=NF;i++){                                     ##Starting a for loop from i value from 3 to NF value in current line.
    if($i ~ /41572/ || $i ~ /90000/ || $i ~ /90002/){     ##Checking condition if any fields value is having keywords mentioned by OP or not.
       flag2++                                            ##Increment variable flag2 here with one.
       if(flag2==1){                                      ##If flag2 value is 1 then print 1st and 2nd column value here.
           printf("%s %s : ",$1,$2)
       }
       flag=1                                             ##Setting variable named flag value to 1 here.
       printf("%s%s",$i,i==NF?ORS:OFS)                    ##Printing value of current field along with check of if i==NF then print new line else print OFS.
    }
  }
}
!flag                                                     ##Checking condition here if !flag then print the current line.
'  Input_file                                             ##Mentioning Input_file name here.