Awk如何打印特定表达式的下一行,但仅当它包含数字时。

huangapple go评论40阅读模式
英文:

Awk how to print the next line of a specific expression but only of it contains a number

问题

这是一个 test.txt 文件

一些文本
另一些文本
...
哈哈
74
哈哈哈
哈哈
789AA

我想要一个 bash 命令,只显示:

74

为此我尝试过:

awk '$0 == "哈哈" {i=1;next};i && i++ <= 1' test.txt

现在显示:

74
789AA

那么,我如何修改这个命令,以便它只显示只包含数字(74)的行?

谢谢

英文:

Here is a test.txt file

sometext
someothertext
...
lol
74
hhhhh
lol
789AA

I want a bash command that only displays:

74

For this I have tried:

awk &#39;$0 == &quot;lol&quot; {i=1;next};i &amp;&amp; i++ &lt;= 1&#39; test.txt

which for now displays

74
789AA

So, how can I augment this command so that it only displays a line that only contains a number (74) ?

Thanks

答案1

得分: 2

这个 awk 应该适用于你:

awk 'p == "lol" && $0+0 == $0; {p = $0}' 文件

74

$0+0 == $0 仅在 $0 包含纯数字时返回 true

英文:

This awk should work for you:

awk &#39;p == &quot;lol&quot; &amp;&amp; $0+0 == $0; {p = $0}&#39; file

74

$0+0 == $0 will return true only when $0 contains a number only.

答案2

得分: 1

用您提供的示例,请尝试以下GNU `awk` 代码。

awk -v RS='\nlol\n[0-9]+\n' 'RT{gsub(/^\n+|\n+$/,"",RT);split(RT,arr,ORS);print arr[2]}' Input_file

英文:

With your shown samples please try following GNU awk code.

awk -v RS=&#39;\nlol\n[0-9]+\n&#39; &#39;RT{gsub(/^\n+|\n+$/,&quot;&quot;,RT);split(RT,arr,ORS);print arr[2]}&#39; Input_file

huangapple
  • 本文由 发表于 2023年7月6日 17:01:22
  • 转载请务必保留本文链接:https://go.coder-hub.com/76627158.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定