简体   繁体   中英

AWK incrementing on column number

I have a large file and some repetitive tasks to execute on columns: in plain language, most tasks would like to

do from i=0 to 9
(col$30+i) = (col$10+i) + (col&20+i)

I would expect at every loop:

i=0 col$30 = col$10 + col$20

i=1 col$31=col$11+col$21

... i=9 col$39=col$19+col$29

I tried explore tags like 'loop over columns', 'increment over column', but nothing came up easily. I could write it for every i, but was wondering if there was a magic trick out there that would be more efficient and transposable to other similar cases. thanks!

dummy data

col10 col11  col20 col21  col30 col31

… 2 42 … 12 1 … 14 43
… 2 83 … 22 1 … 24 84
… 2 45 … 33 4 … 35 49
… 3 61 … 36 3 … 39 64

so at iteration 1, col30 is populated with the correct sums, at iteration2, col2 is populated with the correct sum... etc...

If by colN you mean the N th column, your pseudocode straightforwardly translates to

awk '{ for(i=0; i<=9; ++i) $(30+i) = $(10+i) + $(20+i) }1'

Your dummy data looks like those are column labels in which case you have to parse the first line and figure out which column number corresponds to which label. For your example,

awk 'NR==1 { for(n=0; n<=NF; ++n) if ($n ~ "^col[123][0-9]$") a[$n]=n }
    { for(i=1; i<=9; ++i) a[30+i] = a[10+i] + a[20+i] }1'

as a test harness - you can take it further:

$ awk 'BEGIN{ for(i=0; i<=9;i++) printf("$%d = $%d + $%d\n", i+30, i+10, i+20)}' /dev/null
$30 = $10 + $20
$31 = $11 + $21
$32 = $12 + $22
$33 = $13 + $23
$34 = $14 + $24
$35 = $15 + $25
$36 = $16 + $26
$37 = $17 + $27
$38 = $18 + $28
$39 = $19 + $29

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM