【问题标题】:Not extracting data between two patterns不提取两种模式之间的数据
【发布时间】:2021-03-12 14:38:55
【问题描述】:

我试过这个 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


    【解决方案1】:

    对于您显示的示例,您能否尝试以下操作。

    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

    【讨论】:

    • @user3423407,您好,这是一个经过测试的解决方案,包含您展示的示例,您能否让我知道更多详细信息,这里什么不起作用?谢谢。
    • 嗨@RavinderSingh13 - 感谢您对此进行调查。如果您明确设置模式,则此方法有效。如您所见,我正在使用一个变量——awk -v ff="$file"。由于某种原因,没有提取模式之间的数据。
    • @user3423407,如果您使用 shell 变量将值传递给 awk,请尝试一次 awk -v start="JOHN SMITH-START" -v end="JOHN SMITH-END" '$0 ~ end && found{exit} $0 ~ start{found=1;next} found' Input_file,如果这对您有帮助,请告诉我?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-07-30
    • 2022-01-22
    • 2020-05-08
    • 2023-01-13
    • 1970-01-01
    • 2014-05-20
    • 1970-01-01
    相关资源
    最近更新 更多