csv文件中的重复行

时间:2017-12-01 01:08:30

标签: shell csv sh

我有一个脚本可以从csv文件中删除联系人。

Csv文件类似于:名字,姓氏,电话号码

示例:John,Doe,2109428409

脚本要求用户输入姓氏,整行被删除。如果csv文件中有重复的姓氏,我怎样才能询问用户要删除的两个联系人之一的第一个名字? 这是我的代码

  #!/bin/bash

  echo "Tell Me The Contact's Last Name you want to delete"
  read LastName
  if grep -q $LastName contacts.csv
  then
  sed -i '/'$LastName'/d' contacts.csv
  else
  echo "The surname you typed doesn't exist or isn't valid"
  fi

1 个答案:

答案 0 :(得分:2)

我们可以在您的脚本中添加如下内容,

#!/bin/bash

  echo "Tell Me The Contact's Last Name you want to delete"
  read LastName
  # --------------------------------------------------------#
  if [ $(grep $LastName contacts.csv | wc -l) -gt 1 ];then  # --> check the count of Last name in file
      echo "enter the first name from below list of contact you want to remove"
      grep $LastName contacts.csv     # --> Display list of entries with same Last Name 
      read firstName                  # --> Read First name Input from user
      sed -i '/'$firstName,$LastName'/d' contacts.csv  # --> delete row with first name and Last Name.
  elif [ $(grep $LastName contacts.csv | wc -l) -eq 1 ];then
  # --------------------------------------------------------#
      sed -i '/'$LastName'/d' contacts.csv
  else
      echo "The surname you typed doesn't exist or isn't valid"
  fi