solo2500
Posts: 123
Joined: Sat Jul 09, 2016 12:38 am

Sequential file nameing

Sun Dec 10, 2017 12:14 am

I need to save a file every minute throughout the day and name the file serially. E.g. data0001.txt data0002.txt data0003.txt... data1440.txt
Is there an easy scheme to achieve this using a bash script? I know how to set up a cronjob to run a script... It's just the bash script I'm unsure about.
THANKS for any insight!

Ps... I'm not a programer. Just a pi enthusiast
I'm a total novice, non-programer (...basically a hack.)

W. H. Heydt
Posts: 12655
Joined: Fri Mar 09, 2012 7:36 pm
Location: Vallejo, CA (US)

Re: Sequential file nameing

Sun Dec 10, 2017 12:49 am

You could use a time stamp as part of the file name. If your need for sequential naming isn't exact (you can, after all, get a list of file back in creation order easily enough), you could use the PID as part of the file name. Another approach would be to create a database with a automatic sequence number (e.g. "fm_rowid int not null primary key auto_increment"), then create a new row and read it to get the next number. You could create a separate process that increments a counter each time it is called so it returns the next number in sequence.

asandford
Posts: 1998
Joined: Mon Dec 31, 2012 12:54 pm
Location: Waterlooville

Re: Sequential file nameing

Sun Dec 10, 2017 3:29 am

I have a script that's run daily ( using Node-Red as scheduler):

Code: Select all

#!/bin/bash
cd /root/sqldumps
DATE=$(date +"%Y%m%d%H%M")
/usr/bin/mysqldump  -u root -p<password> --events --all-databases | gzip >$DATE.dump.sql.gz
[this line removed from post as it clears up old dumps]
This will produce a filename like:

Code: Select all

201712091200.dump.sql.gz
That gives a resolution of a minute, if you need second resolution, use this:

Code: Select all

DATE=$(date +"%Y%m%d%H%M%S")

User avatar
rpdom
Posts: 17174
Joined: Sun May 06, 2012 5:17 am
Location: Chelmsford, Essex, UK

Re: Sequential file nameing

Sun Dec 10, 2017 5:58 am

Probably not the easiest way to do it, and could be more flexible when it comes to the filenames and I'm not fully awake yet, but here's something that will work for sequential files within the given spec (data0001.txt to data9999.txt):

Code: Select all

#!/bin/bash

# Generate a sequential file name

lastfile="$(ls data[0-9][0-9][0-9][0-9].txt 2>/dev/null | tail -1)"

# If no files found, start at 0001, else use number of last file and add one
if [ "$lastfile" = "" ]
then
  count=1
else
  lastcount="$(echo "$lastfile" | sed "s/data0*\([1-9][0-9]*\).txt/\1/")"
  let "count = lastcount + 1"
fi

if [ $count -gt 9999 ]
then
  echo "Sequence number $count too high!!!"
  exit 1
fi

FILENAME="$(printf "data%04d.txt" $count)"

echo "New file is $FILENAME"

Return to “Beginners”