Score:0

How to delete a record from a file using bash scipt?

pr flag

I am very new to scripting (one week in) and was trying a program that creates an address book for the user where they can save the details of their friends. First I ask the user to name their address book and I store it in the variable 'abname', then I take the necessary input from the user and print it in the text file abname.txt

My Problem: How can I delete a record corresponding to the id the user has provided? Here is what I did:

#!/bin/bash


id="1"
while(true)
do
    echo -e "\nMenu\n1.Create new Address Book\n2.View all contents of address book\n3.Insert new record\n4.Delete a record\n5.Modify a record\n6.Exit"
    echo -e "\nEnter your choice: "
    read ch
    echo -e "\nYou have selected choice: $ch"
    case $ch in
    1)
    echo -e "\nEnter the name of the address book"
    read $abname;;  

    2)
    echo -e "\nAddress Book: $abname" #the name of the address book doesn't print here for some reason
    echo -e "\nID\t Name\t Age\t Address"
    cat $abname.txt;; #prints all content of the file

    3)
    echo -e "\nId Of Person is: $id"    
    echo -e "\nEnter Name of Person: "
    read name
    echo -e "\nEnter age: "
    read age
    echo -e "\nEnter Address: "
    read addr
    printf "$id\t $name\t $age\t $addr\n" >> $abname.txt
    id=$((id+1));; 

    4)
    echo -e "\nEnter ID of Person who's record is to be deleted: "
    read id
    grep -v "$id" $abname.txt > $abname.txt
    echo "Record is deleted"
    cat abname.txt;;

    5)
    echo -e "\n Todo";;

    6)exit;;
    *) echo -e"\nInvalid choice";;
    esac
done

Additional Help: If the file abname.txt already exists, I want to update my local 'id' variable corresponding to the last person's id in the text file, I tried doing this but it didnt work, what am I missing here?

if [ -e $abname.txt ]
then
    source <$abname.txt>
    id = $id
fi
waltinator avatar
it flag
Always paste your script into `https://shellcheck.net`, a syntax checker, or install `shellcheck` locally. Make using `shellcheck` part of your development process.
mangohost

Post an answer

Most people don’t grasp that asking a lot of questions unlocks learning and improves interpersonal bonding. In Alison’s studies, for example, though people could accurately recall how many questions had been asked in their conversations, they didn’t intuit the link between questions and liking. Across four studies, in which participants were engaged in conversations themselves or read transcripts of others’ conversations, people tended not to realize that question asking would influence—or had influenced—the level of amity between the conversationalists.