0
votes

I have a script that removes Contacts from a csv file.

Csv file is like: First Name,Last Name,Phone Number

Example: John,Doe,2109428409

Script asks user to input Last Name and whole line gets erased. If there's a duplicate last name in the csv file how can I ask the user first name of one of the two contact he wants to delete? Here's my code

  #!/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
did you try using the same method you're already using? - TinyTheBrontosaurus
if this is just for learning, fine, but if you have real data you want to remove duplicates from, consider sort -u -o datFile datFile . Good luck. - shellter
I am actually trying with the same method not really getting the result I want. And yeah this is just for learning. - user9017239
@CGDominator : grep -c outputs the number of matching lines, so instead of testing whether we have a match, you ask for the number of matches and consider 3 cases: 0 matches, 1 match, more than one match. However, your script has other problems: (1) You are testing for the occurance of $LastName in any place of the CSV file, not only in the column for last names. (2) A malevolent user could enter for what you take as his last name, a regexp pattern which wipes out your whole CSV file. By and large, this is not a problem I personally would solve in Posix shell. - user1934428
You have CSV file, which means your data is somewhat structured. That means you really only want to find the value of $LastName in a specific field, not just anywhere in the line. That makes grep inappropriate for this task. - chepner

1 Answers

2
votes

We can add something like below, to your script,

#!/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