Reputation: 19
I have
$string1=\-9-0 ---> $increment1=\-10-0
$string2=\-99 ----> $increment2=\-100
$string3=\-999-0-4 --> $increment3=\-1000-0-4
I need to just increment the first occurring integer to +1 value and integers are prefixed with -
Upvotes: 1
Views: 161
Reputation: 3089
Using awk
awk 'BEGIN{FS=OFS="-"} {$2=$2+1; print}' <<<$string1
Explanation :
We've set Field Separator/ delimiter i.e FS
as -
,
therefore in string -9-0
the second field would be 9
.
We are then incrementing $2
by 1
. Also OFS=-
so that when fields are printed -
is included as delimiter otherwise awk considers space as the delimiter by default.
To store it back to variable :
$ string1=$(awk 'BEGIN{FS=OFS="-"} {$2=$2+1;}1' <<<$string1)
$ echo $string1
-10-0
$ string3=$(awk 'BEGIN{FS=OFS="-"} {$2=$2+1;}1' <<<$string3)
$ echo $string3
-1000-0-4
Upvotes: 1
Reputation: 16997
Using awk
:
One-liner:
awk 'BEGIN{FS=OFS="="}match($2,/[0-9]+/){sub(/[0-9]+/,substr($2,RSTART,RLENGTH)+1,$2)}1' infile
OR even this will work for given input sample
awk -F'[^[:digit:]]+' '{t=$0; sub(/-[0-9]+/,"-"$3+1,t); print t }' infile
Input:
$ cat infile
$string1=\-9-0
$string2=\-99
$string3=\-999-0-4
Output:
$ awk 'BEGIN{FS=OFS="="}match($2,/[0-9]+/){sub(/[0-9]+/,substr($2,RSTART,RLENGTH)+1,$2)}1' infile
$string1=\-10-0
$string2=\-100
$string3=\-1000-0-4
$ awk -F'[^[:digit:]]+' '{t=$0; sub(/-[0-9]+/,"-"$3+1,t); print t }' infile
$string1=\-10-0
$string2=\-100
$string3=\-1000-0-4
Better Readable:
awk '
BEGIN{
FS=OFS="="
}
match($2,/[0-9]+/){
sub(/[0-9]+/,substr($2,RSTART,RLENGTH)+1,$2)
}1
' infile
Upvotes: 1