Ivan M Ivan M - 21 days ago 8
Linux Question

Linux Bash autonumbering of filenames without removing leading zero

With Linux I'd like to automatically add Oracle DB tablespaces within the used format. To do this, I'd like to do an increment of +1 compared to the previous file.

The data files are typically called with this format:

/ora/oradata/tablespace_datafile.dbf
/ora/oradata/tablespace_datafile_02.dbf
/ora/oradata/tablespace_datafile_3.dbf


I was able to extract the
$basefilename
to a variable with
sed 's/[0-9].*//
, which gives as output:
/ora/oradata/tablespace_datafile_


I was also able to extract the numbers with
sed s/[^0-9]//g
to the variable which supposed to be the
$counter
, this gives as output for the above examples:
02
and
3
respectively.

I am, however, having difficulties to add +1 to the
$counter
, without removing the leading zero (
02
should be next
03
, but instead, I get
3
. I am using
let counter++
.

Current code:

basefilename=`echo $connectdb | sed 's/[0-9].*//'`
counter=`echo $connectdb | sed 's/[^0-9]//g'`
let counter++
nextdatafilename=$basefilename$counter'.dbf'


Any suggestions?

Answer

This bash function will increment its numeric argument preserving the leading zeros as required (note that syntax highlighting is confused by the ${parameter##word} parameter expansion syntax):

inc() ( shopt -s extglob; printf "%0${#1}d" $((${1##+(0)} + 1)) )

Examples:

$ echo $(inc 1)
2
$ echo $(inc 01)
02
$ echo $(inc 001)
002
$ echo $(inc 09)
10
$ echo $(inc 009)
010
$ echo $(inc 0)
1

Using it for your situation:

nextdatafilename="$basefilename$(inc $counter).dbf"

Explanation:

  • printf "%0${#1}d" formats the result using at least as many digits as the argument contains
  • shopt -s extglob enables extended pattern matching so that expanding ${1##+(0)} removes all leading zeros (this is necessary, since a number prefixed with a zero is interpreted by bash as octal).
  • the function body is enclosed in parentheses rather than braces so that the effect of shopt -s extglob is local to the function invocation and doesn't affect he caller's environment.
Comments