1

https://stackoverflow.com/a/14348899/15603477
I do understand the following answer. sed -r 's/(.*)(\?cache_version=)([0-9]+)(.*)/echo "\1\2$((\3+1))\4"/ge' file
But I wonder how to do it in awk.
To transform barbaz?cache_version=3fooooo to barbaz?cache_version=4fooooo
The test1 file content as

ello
barbaz?cache_version=3fooooo
bye

The condition is find line contain cache_version= then increase the numeric value in the matched line by 1.
I even fail to locate the matched numeric value, not even mention increase the numeric value.

So far I only locate the specific line by
awk '{if(/cache_version=([[:digit:]+])/) print $1}' < test1

2 Answers 2

2

Assuming the number is always an integer number:

awk 'BEGIN{ FS=OFS="=" }
/cache_version/{ match($NF, /^[0-9]+/); $NF=($NF+1) substr($NF, RLENGTH+1) }1' infile

in the BEGIN{} block we sets the input Field Separator and also Output Field Separator to single equal = char;

then here we are doing awk '/pattern-matching(regexp)/ { "actions" }, which actions within {...} block will be only runs for the line matching with the regexp cache_version;

the match(s, r [, a]) function, return the position in s where the regular expression r occurs, or zero if r is not present, and set the values of RSTART (where the starting position of the regular expression r occur) and RLENGTH (the length in characters of the matched substring/regexp).

Note: I used $NF+1 to force awk to do string to integer conversion as I know that digits are at the starting position of the $NF (while you could sue substr($NF,1, RLENGTH)+1 too), then get the reset of the $NF from the substr($NF, RLENGTH+1).

Note: change regex in the match($NF, /^[+-]?[0-9]*\.?[0-9]+([eE][+-]?[0-9]+)?/), to match almost all type of digits (you might want to use proper printing controls too, see OFMT)

1

You can use the match function in gawk to capture groups into an array and print out each element while incrementing the captured digit:

echo 'barbaz?cache_version=3fooooo' | gawk 'match($0, /(.*cache_version=)([[:digit:]]+)(foo.*)/, a) {print a[1] a[2]+1 a[3]}'

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .