How to keep record of previous operation results in awk?
You can use the match()
function in awk
:
$ cat file
somedata45
somedata47
somedata67
somedata53
somedata23
somedata12
awk '
BEGIN { RS = ""; OFS = "\n"; ORS = "\n\n" }
match($2, /[0-9]+/) { value = (substr($2, RSTART, RLENGTH) + 5) * 100 }
match($3, /[0-9]+/) { $3 = substr($2, 1, RSTART - 1) value }1' file
somedata45
somedata47
somedata5200
somedata53
somedata23
somedata2800
We set the Record Separator to nothing effectively enabling the paragraph mode (separated by blank line). The second line in each paragraph becomes our $2
, third line becomes $3 etc. We set the Output Field Separator to newline. Due to the paragraph mode, we also set Output Record Separator to two newlines. The output will give you an extra newline at the end.
We use the match()
function to identify the start of number. When a match is found, the function populates two variables for us, RSTART
and RLENGTH
indicating when the match starts and how long it is. We use those variables to do our calculation and store the result in variable called value
. We use the substr
function to locate the numbers.
We repeat the same for $3
and this time we use substr
function to print up to where our numbers start and replace the number piece with our variable that contains the calculated value from previous line.
Please refer the String Functions in the user guide for more details.
Update based on real data:
Your real data actually makes it a lot simpler.
awk '
/^uidNumber/ { value = $NF }
/^sambaSID/ {
n = split ($NF, tmp, /-/)
tmp[n] = ((value + 2)* 100)
for (i=1; i<=n; i++) { nf = (nf ? nf "-" tmp[i] : tmp[i]) }
$NF = nf
nf = ""
}1' file
dn: uid=NAME02, ou=data01, dc=data02, dc=data03
uidNumber: 3423
sambaSID: S-1-1-11-1111111-111111111-11111111-342500
dn: uid=NAME03, ou=data01, dc=data02, dc=data03
uidNumber: 3245
sambaSID: S-1-1-11-1111111-111111111-11111111-324700
You look for the line with uidNumber
and capture the last field. When you see a line with sambaSID
you split the last field on -
and modify the last element to your new calculated value. You then use a for loop
to re-assemble your last field.