Steve Snyder <[EMAIL PROTECTED]> writes:
> I've got a question that I hope one of you Bash shell script gurus can
> answer: given a filename that contains a number, how does one create a new
> filename with the number incremented by one?
>
> An example. Suppose I have a file with this name:
>
> filename1234.txt
>
> My goal in this case would be to parse this filename such that the number
> would be extracted then incremented, and a new name, containing the
> incremented number would be created. In this case, I would seek to create
> this filename:
>
> filename1235.txt
Here is one way using awk for the transformation:
echo filename1235.txt|awk -F"." 'BEGIN {OFS="."} {
match($1,/(^[a-z]+)([0-9]+)/,ar)
print ar[1](ar[2]+1),$2}'
Run it:
$ echo filename1235.txt|awk -F"." 'BEGIN {OFS="."} {
> match($1,/(^[a-z]+)([0-9]+)/,ar)
> print ar[1](ar[2]+1),$2}'
filename1236.txt
You didn't mention how the filenames are to be read so I just used a
simple echo.
One caveat. This only works with gnu awk. Like the `awk' with 7.1.
The array operator to the `match' function is a gnu extension.
Probably some cooler way, but this seems to work.
What has happend here is the `match($1,/(^[a-z]+)([0-9]+)/,ar)'
simplified here like match(string,/regexp/,array)'
has used a two part regexp to match first, all the letters in filename
([a-z]+), and second all the digits in 1235 ([0-9]+). Then tucks the
two pieces individually into the array `ar'. Creating a way to access
them individually.
The `-F"."' has set the `Field Separator' (OF) to `.' (dot). creating a
way to reference every thing to the left as field 1 ($1) and everthing
to the right as field 2 ($2). It also has the side effect of removing
the `.' from the output.
That side effect is the reason a BEGIN block sets Output Field
Separator (OFS) like `OFS="."', to replace the `dot' in the output.
Thus far we have set a way to refernce field 1 as `filename1235' and
field 2 as `txt'. We've put `filename' and `1235' into an array as
two separate elements.
So printing then is just a matter of referencing the correct part and
doing the math on one of them. (ar[2] + 1)
print ar[1](ar[2] + 1),$2
Oh, and the comma tells awk to insert an `OFS'.
_______________________________________________
Seawolf-list mailing list
[EMAIL PROTECTED]
https://listman.redhat.com/mailman/listinfo/seawolf-list