【问题标题】:logical and (&&) while searching for patterns in text file in bash [duplicate]在bash中搜索文本文件中的模式时的逻辑和(&&)[重复]
【发布时间】:2021-03-26 08:07:00
【问题描述】:

在下面的代码中,我试图提示用户搜索,1) 数字,2) 偶数或奇数,3) 大数或小数。如果用户的号码存在并且他们为上述提示输入了“奇数”和“小”,那么我希望简单地输出document.txt中的所有数字。附:我知道这没有多大意义,因为您会期望对奇数和小数进行特定搜索,而不仅仅是回显文件中的所有数字,但这就是我正在做的事情。

#!/bin/bash

file1=document.txt
read -p 'Enter the number to be searched for: ' num
read -p 'Type "even" for an even number match or "odd" for an odd number match: ' num_type
read -p 'Type "big" for a big number or "small" for a small number: ' num_size
if grep "$num" $file1 && [[ "${num_type}" == "odd" ]] && [[ "${num_size}" == "small" ]]; then
    echo $(grep "$num" "$file1") result
else
    echo "lol"
fi

我遇到的问题是,如果正确输入了上述提示(例如,num 存在,并且用户输入了奇数和小数),那么脚本运行正常。但是,当用户不输入奇数和小数时,脚本以相同的方式运行,除了“lol”这个词被简单地添加到数字列表的底部,我的目标是简单地将“lol”这个词作为只输出。任何帮助将不胜感激。

【问题讨论】:

  • 目前还不清楚这段代码应该做什么。您似乎拼错了一个变量(file1 vs file)并且您没有定义pattern。您能否提供一个minimal reproducible example,其中包含一个简单的示例输入文件(一或两行)以及不同输入情况的预期输出?
  • if grep 的输出将被发送到标准输出;如果这是您要避免的,可能使用grep -q。如果这是您的实际问题,这是一个微不足道且常见的重复。
  • @tripleee 对此感到抱歉,我对脚本进行了更改。我是 bash 新手,所以我不确定如何准确地表达我的问题。但是,我的目标是输出与用户输入匹配的所有数字,即假设他们输入了一个存在的数字,输入一个“奇数”num_type 并输入一个“小”num_size。如果用户没有输入“奇数”num_type 或“小”num_size,那么我只希望脚本输出“lol”。我遇到的问题是,当输入错误提示时,脚本无论如何都会输出所有数字,只需在脚本底部添加 lol。

标签: bash


【解决方案1】:

可能只运行一次grep,然后决定如何处理输出。

#!/bin/bash

file1=document.txt
read -r -p 'Enter the number to be searched for: ' num
read -r -p 'Type "even" for an even number match or "odd" for an odd number match: ' num_type
read -r -p 'Type "big" for a big number or "small" for a small number: ' num_size
if [[ "${num_type}" == "odd" ]] && [[ "${num_size}" == "small" ]] && result=$(grep "$num" "$file1"); then
    echo "$result result"
else
    echo "lol"
fi

我重新排序了 if 条件,因此如果不需要,我们根本不会运行 grep

还要注意read -r的使用。

【讨论】:

    【解决方案2】:
    grep "$num" $file1
    

    正如grep 所做的那样,它输出匹配的行。使用-q 使其静音。

    if grep -q "$num" $file1
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-10-14
      • 1970-01-01
      • 1970-01-01
      • 2018-04-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-08-20
      相关资源
      最近更新 更多