如果在bash的文本文件中找不到记录,如何循环让用户重新输入?

How to loop to let the user to reenter if the record is not found in the text file in bash?

我目前有一个名为student.txt的文本文件,文本文件中有一些记录。 记录格式为StudentID|Name|ContactNumber|EmailAddress,记录如下:

21PMR07222|Steven|011-1234567|steven@yahoo.com
21PMR07123|John|012-3456789|john@yahoo.com
21PMR07221|Amy|017-4567890|amy@gmail.com

下面的代码是检查用户输入的学号在student.txt文件中是否存在:

awk -F'|' -v id="$studentID" '
 == id { found=1
           printf "Name: %s\nContact Number: %s\nEmail Address: %s\n", , , 
         }
END      { if (found==0) {
              printf "The student ID does not exist. Please enter again." 
           }
         }
' < student.txt

用户可以输入学号查询学生详情。如果用户输入的学号在文本文件中不存在,如何循环让用户重新输入学号?

使用您展示的示例,请尝试遵循 shell 脚本(将此程序另存为 shell 脚本,并具有适当的权限,然后 运行 它)。这里我的文件名是 Input_fileawk 程序从那里读取输入。

#!/bin/bash

while true
do
   echo "Please do enter the user id which you want to match from file:"
   read value
   output=$(awk -F'|' -v id="$value" '
       == id { found=1
         printf "Name: %s\nContact Number: %s\nEmail Address: %s\n", , , 
      }
   END{
      if (found==0) {
         printf "The student ID does not exist. Please enter again."
      }
   }
'  Input_file)
Invalid='The student ID does not exist. Please enter again.'
   if [[ "$output" == "$Invalid" ]]
   then
        echo "NO match found, so re-asking user to enter the value now..."
   else
        echo "$output"
        exit
   fi
done

解释: 简单的解释就是,运行在 [=27 中无限循环 while =],这 运行s 直到 awk 程序在 Input_file 中找到完全匹配。所以基本上在一个无限的 while 循环中我是 运行ning awk 命令(由有问题的 OP 本身发布)然后将其输出放入一个变量并检查输出变量是否为 The student ID does not exist. Please enter again. 然后再次它将 运行 循环并要求用户输入详细信息否则它将打印 output 值并退出程序。

请您尝试以下操作:

awk -F'|' '
NR==FNR {name[] = ; num[] = ; addr[] = ; next}
BEGIN {print "Enter student ID"}
 in name {
    printf "Name: %s\nContact Number: %s\nEmail Address: %s\n", name[], num[], addr[]
    next
}
{
     print "The student ID does not exist. Please enter again."
}
' student.txt -

它首先读取student.txt文件,然后要求用户在STDIN中一个一个地输入学生ID。

#!/usr/bin/env bash

prompt='Enter an ID'
result=1
while (( result != 0 )); do
    IFS= read -p "$prompt: " -r studentID
    prompt='The student ID does not exist. Please enter again'

    awk -F'|' -v id="$studentID" '
         == id {
            printf "Name: %s\nContact Number: %s\nEmail Address: %s\n", , , 
            found = 1
            exit
        }
        END { exit !found }
    ' student.txt

    result=$?
done