Mrbattletoad
Mrbattletoad

Reputation: 61

Using awk to increment specific characters

I have a file where field 11 contains the following string

FP6000

And i need to increment the final 4 digits +1 each time and overwrite contents of the script with the new number

So increment to FP6001

I've used the following in the past which worked fine but these were all digits no letters

awk '{$11=$11+1}1' $FILE > tmp && mv tmp $FILE

What am i missing here?

Upvotes: 0

Views: 493

Answers (5)

The fourth bird
The fourth bird

Reputation: 163362

If you print just $11+1 you will get 1 as "FP6000" is a string evaluating to 0 when you add 1 to it.


A variation using gnu awk using a regex with 2 capture groups, setting field 11 to the first group which matches all till before the last digits, followed by an incremented value for group 2

(.*[^0-9])?([0-9]+)$
  • (.*[^0-9])? Optional capture group 1, matching all until the last occurrence of a non digit
  • ([0-9]+) Capture group 2, match 1 or more digits
  • $ End of string

As the first group is optional, it will also work if there are only digits.

awk 'match($11,/(.*[^0-9])?([0-9]+)$/,a) {$11=a[1](++a[2])}1' $FILE > tmp && mv tmp $FILE

Input

1 2 3 4 5 6 7 8 9 10 FP6000 a b c
1 2 3 4 5 6 7 8 9 10 6000 a b c
1 2 3 4 5 6 7 8 9 10 1A2BFP6000 a b c
1 2 3 4 5 6 7 8 9 10 FP6000X a b c

Output

1 2 3 4 5 6 7 8 9 10 FP6001 a b c
1 2 3 4 5 6 7 8 9 10 6001 a b c
1 2 3 4 5 6 7 8 9 10 1A2BFP6001 a b c
1 2 3 4 5 6 7 8 9 10 FP6000X a b c

Upvotes: 0

Ryszard Czech
Ryszard Czech

Reputation: 18611

Also, another GNU awk solution:

awk '{l=gensub(/[0-9]+$/, "", 1); num=gensub(/^[^0-9]+/, "", 1); print l (num + 1)}' file

I.e., l is the word, num is the number. Once obtained, increment the num and print them.

Upvotes: 0

dawg
dawg

Reputation: 103864

Here is a perl to do that:

perl -lnE 'say $1.($2+1) if m/^([^\d]+)(\d+)/' file
FP6001

Upvotes: 0

Ed Morton
Ed Morton

Reputation: 203615

Given this input file:

$ cat file
1 2 3 4 5 66 7 8 9 10 FP6000 12 13

With GNU awk for the 4th arg to split():

$ awk '{split($11,lets,/[0-9]+$/,digs); $11=lets[1] digs[1]+1} 1' file
1 2 3 4 5 66 7 8 9 10 FP6001 12 13

or with any awk:

$ awk 'match($11,/[0-9]/){$11=substr($11,1,RSTART-1) substr($11,RSTART)+1} 1' file
1 2 3 4 5 66 7 8 9 10 FP6001 12 13

Upvotes: 1

anubhava
anubhava

Reputation: 785196

Use any version awk like this:

s='FP6000'
awk '{f=$1; sub(/[0-9]+$/, "", f); sub(/^[^0-9]*/, "", $1); print f ($1+1)}' <<< "$s"

FP6001

We store $1 in variable f then remove all digits in the end. From $1 we strip out all non-digits from start and then append f and $1+1 together for printing.

Upvotes: 2

Related Questions