首页 > 解决方案 > 找出一个特定的字符并相应地执行搜索?

问题描述

我正在尝试根据要在其后续行中查找剩余字段值的字符来查找两个字符

123456Baadvvdwhbdwbdhw test1 test2 test3 test4 test5
test1 here is the test.
test2 here is the test.
here is line to skip.
here is another line to skip.
test3 here is the test.
here is another line to skip.
123415341636b121313131 test1 test2 test3 test4 test5
here is another line to skip...
here is test5 found.

条件1:检查第一个字段是否有B(直到找到下一个b OR B)然后从第二个字段开始查看它们的值是否存在于其后续行中,如果它们存在则打印它们(如果在至少找到 1 个匹配项)

条件 2:检查第一个字段是否有 b 然后在所有后续行中查找最后一个字段(直到在两个条件中都找到下一个 b 或 B),如果至少有 1 个后续行在其中找到最后一个字段作为匹配项,则打印具有 b 的行。

上述示例的预期输出将是:

123456Baadvvdwhbdwbdhw test1 test2 test3 test4 test5
test1 here is the test.
test2 here is the test.
test3 here is the test.
123415341636b121313131 test1 test2 test3 test4 test5
here is test5 found.

因为我正在学习脚本,所以我已经尝试过这样的点点滴滴:

awk '$1 ~ "B"' file to get first field has B or not

要获取从第二个字段到最后一个字段的字段,我使用了如下命令:

awk '{​​​​​​​for(i=2;i<=NF;i++){​​​​​​​print $i}​​​​​​​}​​​​​​​'

但我不知道如何在一个 awk 中做到这一点,任何指导都非常感谢

标签: shellawk

解决方案


这是一个可以完成这项工作的 awk 命令:

awk 's != "" {for (i=1; i<=NF; ++i) if (index(s, " " $i " ")) {print; next}} $1 ~ /[Bb]/ {print; $1=""; s = $0 " "}' file

123456Baadvvdwhbdwbdhw test1 test2 test3 test4 test5
test1 here is the test.
test2 here is the test.
test3 here is the test.
123415341636b121313131 test1 test2 test3 test4 test5
here is test5 found.

更易读的版本:

awk '
s != "" {
   for (i=1; i<=NF; ++i)
      if (index(s, " " $i " ")) {
         print
         next
      }
}
$1 ~ /[Bb]/ {
   print
   $1 = ""
   s = $0 " "
}' file

推荐阅读