Operating System - HP-UX
1834207 Members
2618 Online
110066 Solutions
New Discussion

script question: update fields in a txt file

 
yyghp
Super Advisor

script question: update fields in a txt file

Hi there,

I am going to scan a txt file every 5 minutes, and will update the column(s) in the file depends on the current situation.
For example: itemprice.txt

CPU 110
Memory 80
Vediocard 50
...

I need to update the numbers every time I scan this file.
How can I script this?
Thanks a lot!

while read -r col1 col2
do
# read the price from database
# want to update $col2, and write to the file, but how to do here?

done < itemprice.txt
4 REPLIES 4
yyghp
Super Advisor

Re: script question: update fields in a txt file

don't want to create another temp file to achieve this.
A. Clay Stephenson
Acclaimed Contributor

Re: script question: update fields in a txt file

You really can't as described. Textfiles have varying record lengths so there is no way to simply update a line. Whay you do is rewrite the entire file as a temporary file then mv the temporary file to the original.

typeset TDIR=${TMPDIR:-/var/tmp}
typeset T1=${TDIR}/X${$}_1.tmp

typeset INFILE=itemprice.txt
typeset col1=""
typeset col2=""
typeset NEWCOL2="xxx"
while read -r col1 col2
do
# do whatever to set ${NEWCOL2}
echo "${col1} ${NEWCOL2}" >> ${T1}
done < ${INFILE}
mv ${T1} ${INFILE}

There are much more efficient ways to do this using perl, awk, or sed but you seemed to want a shell approach.

If it ain't broke, I can fix that.
Rodney Hills
Honored Contributor

Re: script question: update fields in a txt file

If it a specific list of items you want to update, then keep that list in a file without the price and read it in, example-

exec >yourtextfile
for x `cat listofthings` ; do
newprice=`lookupdb $x`
echo $x $newprice
done

Where-
- yourtextfile is where to put the results
- listofthings is just the col 1 items
- lookupdb is the program to look up price

HTH

-- Rod Hills
There be dragons...
Sandman!
Honored Contributor

Re: script question: update fields in a txt file

Hello

It all depends on how you're reading the item prices from the database and how you're storing them? Whether you are using shell or database variables for storing the item prices read from the database? It will help if you could be specific.

thanks!