这是从data.txt文件中删除员工。在用户输入要删除的ID之后,我想编程只搜索文件的第一列(Emp ID列)而不是整个文件的数据。 我已经编写了代码,但它似乎会搜索txt文件中的所有数据。
我该如何改进呢?
代码:
Payroll =data.txt
echo
echo "[Option: $input]"
echo -e "${UBlue}Removing employee record: "
echo -e "Please enter the employee's ID.${NoColor}"
echo
echo -en "Employee ID: "
read empid_search
if [ `count_lines "^${empid_search},"` -eq 0 ]
then
echo "Error: This particular record does not exist!!"
else
echo "Please verify removal of this employee's record: "
echo -en "Employee's Details: "
locate_lines "^${empid_search}"
confirm "Confirm remove?[y/n]"
if [ $? -ne 0 ]
then
echo "Entry has not been deleted.."
else
cp $PAYROLL tmpfile
grep -vi "$empid_search" tmpfile > $PAYROLL ; rm tmpfile
echo "Entry is deleted from records.."
fi
fi
echo -en "Hit [Enter] to return to main menu..."
read
文字档案:
1,James,Manager,Admin,1300
2,Sally,Executive,Sales,2000
3,John,CEO,xpy,2
答案 0 :(得分:2)
你快到了。只是在grep命令中缺少^
和,
。
grep -vi "^${empid_search}," tmpfile > $PAYROLL
注意:最好将变量名称括在{}
也可以尝试使用sed
。它可以进行就地删除,避免需要 tmpfile
sed -i "/^${empid_search},/d" $PAYROLL
使用awk
的另一种变体。处理格式良好的 csv 文件时更强大。
awk -F, '$1!="'${empid_search}'"' tmpfile > $PAYROLL