【问题标题】:Detect whether sentence contains a word in a file检测句子是否包含文件中的单词
【发布时间】:2016-05-27 08:50:39
【问题描述】:

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

输入:

A sentence that contains the word, word1.

字文件:

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]

【问题讨论】:

  • 您的wordfile 是什么样的?我认为这可能就像grep -Fqf wordfile <<<"$input" && echo 'found a word' 一样简单。

标签: bash input grep word-list


【解决方案1】:

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

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

【讨论】:

  • 简单的grep -Eqf wordfile &amp;&amp; echo "found" 可能也可以工作
  • @hek2mgl 我不确定我是否会调用扩展正则表达式模式-E 比使用固定字符串模式更简单! ;)
  • 哦,当然。 -F 也有意义(实际上是在问题中使用,以为是-E)。我只是指出 grep 可以直接读取$input。
  • ./core.sh:第 181 行:需要条件二元运算符 ./core.sh:第 181 行:-Fqf' ./core.sh: line 181: elif [[ grep -Fqf 'vocabulary/lists/greeting' 附近的语法错误
  • 你不需要(不应该)在这个命令中使用[[。你可以使用if grep -Fqf wordfile &lt;&lt;&lt;"$input"; then...。
【解决方案2】:

试试这个:

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

【讨论】:

    猜你喜欢
    • 2018-04-21
    • 1970-01-01
    • 2020-07-06
    • 1970-01-01
    • 2021-07-16
    • 2011-10-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多