我有一个简单的“学生” csv文件,其中包含5列和几行,第一列用于名称。我只想提示用户输入一个名称,看看是否在csv文件中有该名称,但是它不起作用,我也不知道为什么。另外,如果不想找到该程序,我也不想退出,只想打印一条消息
read -p "What is your name?: " arg1
if grep -q arg1 "$names.csv"; then
$ printf "%s\n" "We got you!"
else
$ printf "%s\n" "Sorry, you are not on the list!"
带有输入的csv文件:
Name,R1, R2 , R3 , R4
James,"35,587","55,800,000,000","1,567,988","491,000,000,000"
Tom,"16,000","11,300,000,000","706,250","120,000,000,000"
Sarah,"3,069","1,180,000,000","384,490","7,200,000,000"
答案 0 :(得分:2)
请您尝试以下操作(由于OP尚未提及示例,因此无法对其进行测试)。
cat script.ksh
read -p "What is your name?: " arg1
if grep -q "$arg1" "names.csv"
then
printf "%s\n" "We got you!"
else
printf "%s\n" "Sorry, you are not on the list!"
fi
问题已在OP的代码中解决:
$
添加到变量arg1
中,否则将arg1
视为字符串,同时将其grep到names.csv
文件中。$
前面不必要的printf
。fi
以完成if
块,请参见手册页,每个if
都应以fi
结尾以完成其块。EDIT1: 已通过自己创建的示例进行了测试:
让我们说以下是我们的Input_file。
cat Input_file
"singh","abc_test","1","2","3"
"abc","singh","1","2","4"
"1","2","3","4","5"
脚本如下:
cat script.ksh
read -p "What is your name?: " arg1
if grep -q "$arg1" "Input_file"
then
printf "%s\n" "We got you!"
else
printf "%s\n" "Sorry, you are not on the list!"
fi
现在,当我运行以下代码时,我得到了输出。
./script.ksh
What is your name?: singh
We got you!
EDIT2: :如果您想在任意字段中匹配 "singh"
之类的精确字符串的csv,然后尝试以下操作。
cat script.ksh
read -p "What is your name?: " arg1
if grep -q "\"$arg1\"" "file"
then
printf "%s\n" "We got you!"
else
printf "%s\n" "Sorry, you are not on the list!"
fi
上述脚本的测试:
./script.ksh
What is your name?: singh1
Sorry, you are not on the list!
./script.ksh
What is your name?: singh
We got you!