如何检测文本文件中大于 n 的一系列“空洞”(孔、与模式不匹配的线)?

2024-05-05

Case scenario:

$ cat Status.txt
1,connected
2,connected
3,connected
4,connected
5,connected
6,connected
7,disconnected
8,disconnected
9,disconnected
10,disconnected
11,disconnected
12,disconnected
13,disconnected
14,connected
15,connected
16,connected
17,disconnected
18,connected
19,connected
20,connected
21,disconnected
22,disconnected
23,disconnected
24,disconnected
25,disconnected
26,disconnected
27,disconnected
28,disconnected
29,disconnected
30,connected

可以看出,有“空洞”,将其理解为带有“断开”的行序列文件内的值。

事实上,我想要detect这些“洞”,但如果我可以设置一个minimum n缺失的数字在序列中。
即:对于“n=5”,可检测到的孔将是7... 13部分,因为序列上至少有 5 个连续的“断开连接”。然而,失踪的17在这种情况下不应被视为可检测到。同样,在第 21 行,他得到了有效的断开连接。

就像是:

$ detector Status.txt -n 5 --pattern connected
7
21

...可以这样解释:

- Missing more than 5 "connected" starting at 7.
- Missing more than 5 "connected" starting at 21.

我需要编写这个脚本Linux外壳,所以我正在考虑编写一些循环,解析字符串等,但我觉得这是否可以通过使用来完成Linux shell 工具也许还有一些更简单的编程。有办法吗?

即使像这样的小程序csvtool是一个有效的解决方案,一些更常见的 Linux 命令(例如grep, cut, awk, sed, wc...等)在使用嵌入式设备时对我来说可能是值得的。


#!/usr/bin/env bash
last_connected=0
min_hole_size=${1:-5}  # default to 5, or take an argument from the command line
while IFS=, read -r num state; do
  if [[ $state = connected ]]; then
    if (( (num-last_connected) > (min_hole_size+1) )); then
      echo "Found a hole running from $((last_connected + 1)) to $((num - 1))"
    fi
    last_connected=$num
  fi
done

# Special case: Need to also handle a hole that's still open at EOF.
if [[ $state != connected ]] && (( num - last_connected > min_hole_size )); then
  echo "Found a hole running from $((last_connected + 1)) to $num"
fi

...发出,给定标准输入上的文件(./detect-holes <in.txt):

Found a hole running from 7 to 13
Found a hole running from 21 to 29

See:

  • Bash 常见问题解答#1 http://mywiki.wooledge.org/BashFAQ/001 - 如何逐行(和/或逐字段)读取文件(数据流、变量)?
  • 条件表达式 http://wiki.bash-hackers.org/syntax/ccmd/conditional_expression -- the [[ ]]用于确保在不引用扩展的情况下安全地进行字符串比较的语法。
  • 算术比较语法 http://wiki.bash-hackers.org/syntax/arith_expr#comparisons-- 有效日期$(( ))在所有符合 POSIX 标准的 shell 中;也可以在没有扩展副作用的情况下使用(( ))作为 bash 扩展。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何检测文本文件中大于 n 的一系列“空洞”(孔、与模式不匹配的线)? 的相关文章

随机推荐