开发者

Awk script for substracting from the above field

开发者 https://www.devze.com 2023-01-29 11:40 出处:网络
Hi I have my input file with one field: 30 58 266 274 296 322 331 I need the output to be the difference of 2nd and 1st rows(58-30=28) and 3rd and 开发者_StackOverflow社区2nd rows(266-58=208) and s

Hi I have my input file with one field:

30
58
266
274
296
322
331

I need the output to be the difference of 2nd and 1st rows(58-30=28) and 3rd and 开发者_StackOverflow社区2nd rows(266-58=208) and so on. my output should look like below:

30 30
58 28
266 208
274 8

any help please?


data=`cat file | xargs`
echo $data | awk '{a=0; for(i=1; i<=NF;i++) { print $i, $i-a; a=$i}}'

30 30
58 28
266 208
274 8
296 22
322 26
331 9

Update upon comment Without cat/xargs:

awk '{printf "%d %d\n", $1, $1-a; a=$1;}' file


You don't actually need the for loop from Khachick's answer as Awk will go through all the rows anyway. Simpler is:

cat file | awk '{ BEGIN { a=0 }; { print $1, $1-a; a=$1 }'

However it is also possible to skip the first row that you don't really want by initialising a variable in the BEGIN block and not doing the print if the variable is so initialised before changing its value. Sort of like:

BEGIN { started=0 }; { if(0 == started) { started = 1 } else { print $1, $1-a } }
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号