将用户输入与文件内的列表进行比较

Comparing user input with a list inside the file

感谢您的宝贵时间。

我对 SHELL SCRIPT 有一个要求,我必须在其中获取用户输入并将其与文本文件中的内容列表进行比较,看看输入是否与任何一行匹配在文本文件中。

场景如下: 猫 fruits.txt 苹果 橙 芒果 葡萄

输入水果名称:醋栗 店里没有啊!! 输入水果名称:苹果 欢迎来到苹果的世界!

如有任何帮助,我们将不胜感激。 :(

假设您有一个文件 fruitlist.txt,其中存储了您的水果列表(或其他)。

fruitlist.txt的内容:

red apple
green apple
orange
mango
grapes

注意,每个水果后面都有一个换行符。

以下 bash 脚本需要水果列表文件的路径作为第一个参数:

#!/bin/bash

listFile=

if [ -f "$listFile" ]; then
    echo "Type 'q' or 'Q' to exit the script."
    echo "-----------------------------------"
    while true; do
        read -p "Type the fruit name: " fruit
        if [ "$fruit" = "q" ] || [ "$fruit" = "Q" ]; then
            break
        elif [ "$(grep "$fruit" "$listFile")" = "$fruit" ]; then
            echo "The fruit '$fruit' is in the list."
        else
            echo "The fruit '$fruit' is not in the list."
        fi
    done
    echo "-----------------------------------"
else
    echo "No fruit list file specified."
fi

exit 0

声明

if [ -f "$listFile" ]; then

测试水果列表文件是否存在。

命令

read -p "Type the fruit name: " fruit

将水果名称读入变量fruit。

无限循环中的第一个if

if [ "$fruit" = "q" ] || [ "$fruit" = "Q" ]; then
    break

检查用户是否要退出脚本。以下

elif [ "$(grep "$fruit" "$listFile")" = "$fruit" ]; then
    echo "The fruit '$fruit' is in the list."
else
    echo "The fruit '$fruit' is not in the list."
fi

检查是否可以在水果列表文件中找到输入的水果。单独使用 grep 命令可以找到包含水果名称的每一行。假设您有一个包含两个名称部分的水果,例如 'red apple'、'green apple' 等。用户将输入 'red' 并且 if 将为真。现在 if 语句中的 "" = "" 确保,如果用户输入 'red',该语句将不正确,因此不会在列表中找到水果。