0 Replies - 1336 Views - Last Post: 08 December 2010 - 06:31 AM

#1 nathanpc  Icon User is offline

  • SCIENCE!
  • member icon

Reputation: 113
  • View blog
  • Posts: 1,171
  • Joined: 31-July 09

Using Files As Databases

Posted 08 December 2010 - 06:31 AM

Description: This snippet shows you how to use files like databases on Shell Script. With it you can search on a file, add records to it, delete records and list all the records on your database/file

This example was made simple to gave you just an introduction to this kind of stuff.Simple example of how you can list, add, remove and search on a file, using it like a database. Teaching a bit of how to use the grep function and file I/O
#!/bin/sh
# Access AddressBook file and use it as a database

# Variables
name=$1
number=$2
db=AddressBook

### AddressBook File Example ###
# Maria Daher	(27)5564-4392  #
# Nathan Campos	(27)3325-9732  #
# Thiago B.	(32)5302-4892  #
# Lucas Pinher	(23)0982-2389  #
# Eduardo V.	(75)9234-8234  #
################################

# Listing what's on the file
cat $db

# Searching inside the file for the term inputted as the first argument
grep "$name" $db

# Adding someone on the file
echo "$name	$number" >> $db    # Add a new input on the file
sort -o $db $db    # Organize the db/file content

# Deleting records from the file
grep -v "$name" $db > /tmp/$$    # Create the new file without the choosen record on /tmp/(PID)
mv /tmp/$$ $db    # Overwrite the file with the one without the record removed


Is This A Good Question/Topic? 0
  • +

Page 1 of 1