如何使用bash或python从一组数字中搜索连续数字

时间:2012-11-05 21:19:44

标签: arrays bash

我有一个如下数字列表:

1  0/1
2  1/1
3  1/1
4  1/1
5  1/1
6  1/1
7  0/1
8  0/1

如果列2对于连续的行是“1/1”,我想报告位置的开始和结束,比如,在这里,它应该是:2-6

我应该如何应用一些简单的bash代码,或者必要时使用python?

非常感谢

2 个答案:

答案 0 :(得分:2)

如果你能够在python中编码,你可以通过以下方式解决它:

  1. 阅读您的文件。
  2. 使用正则表达式创建仅包含第一个数字的列表,如果第二个数字为1/1
  3. 将范围分组。 (hint
  4. 所以代码看起来像:

    import re
    
    # step 1
    with open('filename') as f:
        data = f.read()
    
    # step 2
    list = re.findall(r'(\d+)\s+1/1', data)
    
    # step 3
    # Check the link in the description of the algorithm
    

答案 1 :(得分:0)

Bash解决方案:

#! /bin/bash
unset in                                 # Flag: are we inside an interval?
unset last                               # Remember the last position.
while read p f ; do
    if [[ $f = 1/1 && ! $in ]] ; then    # Beginning of an interval.
        echo -n $p-
        in=1
    elif [[ $f = 1/1 && $in ]] ; then    # Inside of an interval.
        last=$p
    elif [[ $f != 1/1 && $in ]] ; then   # End of an interval.
        echo $last
        unset in
    fi
done