Difference Between Number in the Same Column Using Awk

difference between number in the same column using AWK

Try the following code :

awk '
NR == 1{old = $1; next} # if 1st line
{print $1 - old; old = $1} # else...
' file.txt
1
2
0
6

explanations

  • NR is the ordinal number of the current record from the start of input. Inside a BEGIN action the value shall be zero. Inside an END action the value shall be the number of the last record processed.
  • next statement shall cause all further processing of the current input record to be abandoned. The behavior is undefined if a next statement appears or is invoked in a BEGIN or END
    action.

Measuring difference between 2 numbers in the same column using awk

Here is one method that uses the modulus operator to create an array that stores only the last elements needed for the calculation:

$ awk 'NR>2{print $3-a[(NR-2)%3]}{a[NR%3]=$3}' file
4
17
20
12

As for a good tutorial check out Effective AWK Programming.

Using AWK to compare values in the same column

Like this:

awk 'int($6) && $6 > n{n=$6}END{print n}' file

how to determine if difference between two values falls within range with awk?

Same idea as the above awk

$ awk 'NR==1{p=$1;next} 
{print $1-p,
((p-6)*(p-8)<=0 || ($1-6)*($1-8)<=0)?"+":"-"; p=$1}' file

5 -
2 +
6 +

ps. This checks whether at least one of the values is between the 6,8 range. If you want both change || with &&.

UPDATE: The range check should be based on the span of the two entries as explained in the comments. This should do:

$ awk 'function max(x,y) {return x>y?x:y}; 
function min(x,y) {return x>y?y:x};
NR==1{p=$1;next} {print $1-p,
(max($1,p)<6 || min($1,p)>8)?"-":"+"; p=$1}'

awk a number, character, then the same number

awk to the rescue!

UPDATED

$ awk -v col=2 '{split($col,a,"[/:]")} a[1]!=a[2]' file

1/1: 0/1: a
3/3: 0/2: d
0/2: 0/1: e

Difference between adjacent data rows, with multiple columns

$ cat tst.awk
NR>1 {
for (i=1; i<=NF; i++) {
printf "%2d%s", $i - p[i], (i<NF ? OFS : ORS)
}
}
{ split($0,p) }

$ awk -f tst.awk file
2 2 2 0 -3 -5
2 3 0 3 0 -1

difference between lines in the same column using AWK

Given:

$ echo "$test" 
aaaa;12
aaaa;13
bbbb;11
bbbb;9
cccc;9
cccc;8

You can do something like:

$ echo "$test" | awk -F ";" 'function abs(v) {return v < 0 ? -v : v} $1==l1 && abs($2-l2)==1 {print l1 FS l2 RS $0} {l1=$1;l2=$2}'
aaaa;12
aaaa;13
cccc;9
cccc;8


Related Topics



Leave a reply



Submit