首页 > 解决方案 > 不提取两种模式之间的数据

问题描述

我试过这个 awk 命令,但由于某种原因,它没有打印出两种模式之间的数据

这是我的整个 awk 命令

for file in `cat out.txt`
do
      awk -v ff="$file" 'BEGIN {print "Start Parsing for"ff} /ff-START/{flag=1; next}/ff-END/{flag=0}flag;  END{print "End Parsing"ff}' data.txt
done

这是data.txt的内容

JOHN SMITH-START
Device,Number
TV,1
Washing Machine,1
Phones, 5
JOHN SMITH-END
MARY JOE-START
Device,Number
TV,3
Washing Machine,1
Phones, 2
MARY JOE-END

这里还有 100 多条类似的行,模式是 NAME-START 和 NAME-END。因此,例如 JOHN SMITH-START 是第一个模式,然后 JOHN SMITH-END 是第二个模式,我想提取这两者之间的数据,即

Device,Number
TV,1
Washing Machine,1
Phones, 5

但我得到的输出是

Start Parsing forJOHN SMITH
End ParsingJOHN SMITH

out.txt 的内容是

JOHN SMITH
MARY JOE

标签: awk

解决方案


使用您显示的示例,您能否尝试以下操作。

awk '/JOHN SMITH-END/ && found{exit} /JOHN SMITH-START/{found=1;next} found' Input_file

说明:为上述添加详细说明。

awk '                         ##Starting awk program from here.
/JOHN SMITH-END/ && found{    ##Checking condition if line contains JOHN SMITH-END and found is SET then do following.
  exit                        ##exiting from program from here.
}
/JOHN SMITH-START/{           ##Checking condition if line contains JOHN SMITH-START then do following.
  found=1                     ##Setting found to 1 here.
  next                        ##next will skip all further statements from here.
}
found                         ##If found is set then print that line.
' Input_file                  ##Mentioning Input_file name here.

注意:如果您想在awk搜索中使用变量,请尝试以下操作:

awk -v start="JOHN SMITH-START" -v end="JOHN SMITH-END" '$0 ~ end && found{exit} $0 ~ start{found=1;next} found' Input_file


推荐阅读