Register
It is currently Sat Dec 20, 2014 2:28 pm

Appending incremental numbers to a file


All times are UTC - 6 hours


Post new topic Reply to topic  [ 2 posts ] 
Author Message
 PostPosted: Wed Nov 16, 2011 3:24 pm   

Joined: Wed Nov 16, 2011 3:19 pm
Posts: 1
I have a script where a user enters in information which is read as a variable, then appends the information to a file. Each time it appends it is a new line, and I would like each new line in the appended file to be an incremental number.

if [ $ANSWER2 = "y" -o $ANSWER2 = "Y" ]
then
echo -e "$NAME\t$RELATION\t$PHONE" >> ~/.database

so from my script it will append name, relation and phone variables to .database, but I would like to have it so each new line has an incremented number, starting at 001. I'm fairly new to bash scripting so I'm not sure if I'm posting in the right section.

[edit]

I was playing around a bit and I have a temporary solution, but I don't like how I have two database files and the nl command can make the file a bit messy...

if [ $ANSWER2 = "y" -o $ANSWER2 = "Y" ]
then
echo -e "$NAME\t$RELATION\t$PHONE" >> ~/.database2
fi
nl ~/.database2 > ~/.database


Top
 Profile  
 PostPosted: Wed Nov 16, 2011 4:24 pm   

Joined: Mon Mar 02, 2009 3:03 am
Posts: 579
hi,

I'd rather read last line from .database to get its last registered number
if .database is empty,or doesn't exist num is 1

let's say .database looks like this :
<num>\t<name>\t<relation>\t<phone>

i'd get last num like this:
Code:
IFS=$'\t' read num nm <(tail -1 ~/.database)

and send data in like this:
Code:
printf '%s\t%s\t%s\t%s\n' $num "$name" "$relation" "$phone" >> ~/.database


aside, you'd better not use uppercase variable names (even for readibility), it's reserved for environmental variables, by convention.


Top
 Profile  
Display posts from previous:  Sort by  
Post new topic Reply to topic  [ 2 posts ] 

All times are UTC - 6 hours


Who is online

Users browsing this forum: No registered users and 1 guest


You cannot post new topics in this forum
You cannot reply to topics in this forum
You cannot edit your posts in this forum
You cannot delete your posts in this forum
You cannot post attachments in this forum

Jump to:  


BashScripts | Promote Your Page Too
Powered by phpBB © 2011 phpBB Group
© 2003 - 2011 USA LINUX USERS GROUP