-1

这是从 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
4

1 回答 1

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
于 2013-11-02T07:26:55.823 回答