我想检查输入的值是否是文件中第一行值的重复值。
这是我的代码,但它不起作用
printf "Enter Table Name: "
read tableName
printf "Enter new Value: "
read value
for j in $(awk -F':' '{if(NR>2) printf $1 }' $tableName); do
if(value -eq $j); then
printf "duplicated"
else
printf "not duplicated"
答案 0 :(得分:1)
将代码传递给shellcheck.net,您就可以自己发现问题。
您可以使用grep
代替使用awk
:
printf "Enter Table Name: "
read tableName
printf "Enter new Value: "
read value
if grep -qx -- "$value" <(cut -f2 -d: "$tableName"); then
echo "duplicated"
else
echo "not duplicated"
fi
最好在运行grep
之前验证输入的值:
printf "Enter Table Name: "
read tableName
[[ -z "$tableName" ]] && printf "No value entered for table name.\n" >&2 && exit 1
[[ ! -f "$tableName" ]] && printf "File '%s' does not exist.\n" "$tableName" >&2 && exit 1
printf "Enter new Value: "
read value
[[ -z "$value" ]] && printf "No value entered.\n" >&2 && exit 1
if grep -wq -- "$value" <(cut -f2 -d: "$tableName"); then
echo "duplicated"
else
echo "not duplicated"
fi