2013-03-13 65 views
0

例如有一个文件input.txt检查文本文件是否包含全部10个单词的正则表达式是什么?

我想检查input.txt包含了所有的以下十个字:

catdogfishchickduckcowhorse,...,sheep

请注意,我不在乎它们在文本文件中出现的顺序。

为了兼容性,请尽可能使用基本操作符。

+1

你尝试过什么吗? – alestanis 2013-03-13 20:27:56

+5

你需要使用'正则表达式'吗?看起来像'InStr()'可能更容易...另外,你需要什么语言,他们必须以任何特定的顺序? – 2013-03-13 20:28:39

+1

解析文件并以编程方式检查该条件会不会更容易? – assylias 2013-03-13 20:29:42

回答

0

使用

c=0 
word_list=(word1 word2 word3 word4 word5 word6 word7 word8 word9 word10) 
arr=($(cat input.txt)) # taking advantage of word spliting 

for i in "${word_list[@]}"; do 
    for j in "${arr[@]}"; do 
     if [[ $i == $j ]]; then 
      ((c++)) 
      continue 2 # stop searching the current word 
     fi 
    done 
done 

((c==10)) && echo "true" 

更多I/O版本使用

c=0 
word_list=(word1 word2 word3 word4 word5 word6 word7 word8 word9 word10) 

for i in "${word_list[@]}"; do 
    if grep -q "\b$i\b" input.txt; then 
     ((c++)) 
     continue # stop searching the current word 
    fi 
done 

((c==10)) && echo "true" 
0

此解决方案要求grep支持-o选项。

grep -Fwo -f patternfile.txt inputfile.txt | sort | uniq 

F标志匹配固定字符串,因为关键字是固定的字符串。
w标志为grep命令强制模式只匹配整个单词。
o标志将打印唯一的匹配,每个匹配一行。这是必要的与sortuniq工作的伎俩。

在这个命令链之后,如果一个单词有一个匹配,那么它将在输出中恰好出现一次。这不是完整的解决方案,但我认为这足以让我们继续前进。

patternfile.txt包含您要搜索的词,换行分隔。在你的情况下:

cat 
dog 
fish 
chick 
duck 
cow 
horse 
sheep 
相关问题