Bash 如何打印包含特定数字但不包含以前从未出现过的其他数字的行?

Bash 如何打印包含特定数字但不包含以前从未出现过的其他数字的行?,bash,awk,grep,Bash,Awk,Grep,我有一个包含许多数字的文件,用10个前导数字写,前面临时放“a”,后面放“Z”,以确保脚本不会错误识别数字的开头和结尾。例如: A00000000001Z A00000000003Z,A00000000004Z;A00000000005Z A00000000004Z A00000000005Zsome wordsA00000000001Z A00000000006Z;A00000000005Z A00000000001Z 我需要搜索一个特定的数字,但只输出那些找到数字的行,而以前从未出现过的其

我有一个包含许多数字的文件,用10个前导数字写,前面临时放“a”,后面放“Z”,以确保脚本不会错误识别数字的开头和结尾。例如:

A00000000001Z
A00000000003Z,A00000000004Z;A00000000005Z
A00000000004Z A00000000005Zsome wordsA00000000001Z
A00000000006Z;A00000000005Z
A00000000001Z
我需要搜索一个特定的数字,但只输出那些找到数字的行,而以前从未出现过的其他数字都不在同一行

例如,如果我搜索“0000000001”,它将打印第1、3和5行:

A00000000001Z
A00000000004Z A00000000005Zsome wordsA00000000001Z
A00000000001Z
它可以打印第3行,因为其他数字“0000000000 4”和“0000000000 5”以前出现在第2行中

如果我搜索“0000000000 5”,它将打印第3行:

A00000000004Z A00000000005Zsome wordsA00000000001Z
它不会打印第2行,因为其他数字“0000000000 3”和“0000000000 4”以前从未出现过

到目前为止,我已经解决了这个问题:

# search for the line and print the previously appearing lines to a temporary file
grep -B 10000000 0000000001 file.txt > output.temp

# send the last line to another file
cat output.temp | tail -1 > output.temp1
sed -i '$ d' output.tmp > output.temp2

# search for numbers appearing in output.temp2
for i in 1 .. 1000000 NOT original number
     a=`printf $010d $i`
     if [ $a FOUND in output.temp2]
     then
          # check if was found in the previous line
          if [ $a NOT FOUND in output.temp1]
          else

          fi    
     fi
done < ./file.txt
#搜索该行并将以前出现的行打印到临时文件中
grep-B 100000000000000001 file.txt>output.temp
#将最后一行发送到另一个文件
cat output.temp | tail-1>output.temp1
sed-i'$d'output.tmp>output.temp2
#搜索output.temp2中出现的数字
因为我在1。。1000000不是原始号码
a=`printf$010d$i`
if[$a在output.temp2中找到]
然后
#检查是否在前一行中找到
如果[$a未在output.temp1中找到]
其他的
fi
fi
完成<./file.txt

如何仅打印包含特定数字的行,而不打印文件中以前从未出现过的其他数字?

严格来说不是bash,但在Python2中,您可以从shell运行:

#!/usr/bin/env python

import re
import sys

def find_valid_ids(input_file, target_id):
    with open(input_file) as f:
        found_ids = set()
        for line in f.readlines():
            ids = set(re.findall(r'A\d+Z', line))
            if (target_id in ids and
                (len(ids - found_ids) == 0 or
                 (len(ids) == 1 and target_id in ids))):
                print line.strip('\n')
            found_ids |= ids

if __name__ == "__main__":
    try:
        find_valid_ids(sys.argv[1], sys.argv[2])
    except IndexError as e:
        print 'Usage: ./find_valid_ids.py input_file target_id'

因此,如果您将上述内容保存为
find\u valid\u ids.py
,您将
$chmod+x find\u valid\u ids.py
并像
$/find\u valid\u ids.py那样运行它,您的\u input\u file.txt A00000000001Z

您无法使用grep执行此操作,它没有任何内存,但您应该可以使用
awk
执行此操作。请说明您已经尝试了什么,所以这不是免费的编码服务。我在解析您的需求时遇到了问题,“没有以前出现过的其他数字”中的双负数令人困惑。向我们展示真实的数据文件,并写下您为什么喜欢这种类型的解决方案。这可能有助于我们了解您的问题并解决它。