difference between number in the same column using

2020-03-01 07:50发布

I have a file containing one column of number:

1
2
4
4
10

I would like to calculate the difference between each number using awk. The output should be like this :

1
2
0
6

How can I do it ?

4条回答
时光不老,我们不散
2楼-- · 2020-03-01 08:30

Just to make it shorter ...

% awk 'NR>1{print $1-p} {p=$1}' file
1
2
0
6
查看更多
做个烂人
3楼-- · 2020-03-01 08:36

In case awk is not a strict requirement, a shell solution:

set -- $(< file)
p=$1; shift; while (($# > 0)); do echo $(($1 - p)); p=$1; shift; done

DRYer

set -- $(< file)
while (($#>0)); do [[ -n $p ]] && echo $(($1-p)); p=$1; shift; done
查看更多
仙女界的扛把子
4楼-- · 2020-03-01 08:37

Code for GNU

$awk '{p=f;f=$1} NR>1{print f-p}' file
1
2
0
6
查看更多
男人必须洒脱
5楼-- · 2020-03-01 08:39

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.
查看更多
登录 后发表回答