Nandakumar
Content Network

You are not logged in.
Click here to login.

Some part of this library is not public. You must register to get exclusive access. If you are already registered, click here to login.


Shell Programming >> 2017

Phone Book Using Shell and AWK

By | | License: proprietary


Code

Updated on Apr 5, 2017, 12:14 PM IST: Added 'Display All' feature.

#!/bin/bash
# Nandakumar.co.in v0.1.4

while [ 1 ]; do
	echo -e "\nPHONE BOOK"
	echo -e "==========\n"

	echo -e "Please select an option from the following: \
	         \n\t1) Insert\n\t2) Display All\n\t3) Search\n\t4) Delete\n\t5) Exit\n"
	echo "Enter your choice: "
	read choice

	case $choice in
		1)
			echo -e "\nINSERT:"
			echo -n "Enter the name: "
			read name
			echo -n "Enter the phone number: "
			read phone
			echo -e "$name\t$phone" >> contacts.csv;;

		2)
			echo -e "\nALL RECORDS:"
			if [ -e contacts.csv ]; then
				echo -e "Name\tPhone no."
				cat contacts.csv
			else
				echo "Sorry, no records found."
			fi;;

		3)
			echo -e "\nSEARCH:"
			echo -n "Enter the query: "
			read query
			echo -n "Search by name or number (enter 1 for name, anything else for number): "
			read method

			retval=$(cat contacts.csv | awk -v q="$query" -v meth="$method" '{
				FS="\t"
				if( (meth == 1 && tolower($1) == tolower(q)) ||
				    (meth != 1 && tolower($2) == tolower(q)) )
				{
					print "Name: " $1
					print "Number: " $2
				}
			}')

			if [ -n "$retval" ]; then
				echo -e "\n$retval\n"
			else
				echo "Sorry, $query not found."
			fi
			echo "Press Enter to continue..."
			read something;;

		4)
			echo -e "\nDELETE:"
			echo -n "Enter the name: "
			read name

			if [ -e contacts_tmp.csv ]; then
				rm contacts_tmp.csv
			fi

			cat contacts.csv | awk -v name="$name" '{
				if(tolower($1) != tolower(name)) {
					print $line # $line has no significance here. Simple print would work.
				}
			}' > contacts_tmp.csv

			mv contacts_tmp.csv contacts.csv;;

		5)	exit;;

		*)
			echo "Invalid choice.";;
	esac
done

Keywords (click to browse): awk phonebook contacts string-processing shell sh bash linux gnu unix script programming command-line

Phone Book Using Shell and AWK | Nandakumar Content Network
Copyright © 2015, 2016, 2017 Nandakumar Edamana.