检测句子是否包含文件中的单词

Detect whether sentence contains a word in a file

当用户输入内容时,脚本会检查输入是否包含 wordfile 中的任何单词。

输入:

A sentence that contains the word, word1.

Word 文件:

word1
word2
word3

代码:

[[ -z $(cat 'vocabulary/lists/wordfile' | grep -Fe $($input//" "/"\|")) ]]

输出:

> [WORD]
./core.sh: line 168: [WORD]// /\|: No such file or directory
grep: option requires an argument -- 'e'
Usage: grep [OPTION]... PATTERN [FILE]...
Try 'grep --help' for more information.
[WORD]

试试这个:

[[ -n $(sed -n -f <(sed 's/^/\//g;s/$/\/p/g' vocabulary/lists/wordfile) <<< "$input") ]] && echo Found

我认为这可能是您需要的:

grep -Fqf wordfile <<<"$input" && echo 'found a word'

这会使用文件 wordfile (-f wordfile) 中的模式进行固定字符串匹配 (-F) 并使用 -q 在任何匹配成功时静默退出找到了。

例如:

$ cat wordfile
apple
ball
cat
$ input='a string containing the word ball'
$ grep -Fqf wordfile <<<"$input" && echo 'found a word'
found a word