Bash 在列中减去数字

Bash 在列中减去数字,bash,Bash,在一个文件中,我有一列数字和10个元素。我想从第三个数字中减去第一个,从第四个数字中减去第二个,从第五个数字中减去第三个,从第六个数字中减去第四个,依此类推,从第十个数字中减去第八个数字 例如: 10.3456 6.3452 11.2456 5.6666 10.5678 6.4568 14.7777 7.5434 16.5467 8.9999 然后用减法得到一个文件 3rd-1st 4th-2nd 5th-3rd 6th-4th 7th-5th 8th-6th 9th-7th 10th-8th

在一个文件中,我有一列数字和10个元素。我想从第三个数字中减去第一个,从第四个数字中减去第二个,从第五个数字中减去第三个,从第六个数字中减去第四个,依此类推,从第十个数字中减去第八个数字

例如:

10.3456
6.3452
11.2456
5.6666
10.5678
6.4568
14.7777
7.5434
16.5467
8.9999
然后用减法得到一个文件

3rd-1st
4th-2nd
5th-3rd
6th-4th
7th-5th
8th-6th
9th-7th
10th-8th
又快又脏:

$  awk '{a[NR]=0+$0}END{for(i=3;i<=NR;i++)print a[i]-a[i-2]}' file
0.9
-0.6786
-0.6778
0.7902
4.2099
1.0866
1.769
1.4565
$awk'{a[NR]=0+$0}END{for(i=3;i1{print$1-$2}'快速且脏:

$  awk '{a[NR]=0+$0}END{for(i=3;i<=NR;i++)print a[i]-a[i-2]}' file
0.9
-0.6786
-0.6778
0.7902
4.2099
1.0866
1.769
1.4565
$awk'{a[NR]=0+$0}END{for(i=3;i1{print$1-$2}'
#!/bin/bash
#创建一个数组
mapfile-t行<输入文件
输出=()
对于“${!行[@]}”中的索引,请执行以下操作
#检查索引+2是否存在
如果[${lines[$(expr$index+2)]}]];则
#它确实存在,算算吧
输出+=(“$(expr${lines[$index]}+${lines[$(expr$index+2)]}”)
fi
完成
printf“%s\n”${output[@]}>output
#!/bin/bash
#创建一个数组
mapfile-t行<输入文件
输出=()
对于“${!行[@]}”中的索引,请执行以下操作
#检查索引+2是否存在
如果[${lines[$(expr$index+2)]}]];则
#它确实存在,算算吧
输出+=(“$(expr${lines[$index]}+${lines[$(expr$index+2)]}”)
fi
完成
printf“%s\n”${output[@]}>output
perly dog

perl -ne '$a{$.}=$_;print $_-$a{$.-2}."\n" if $a{$.-2}' file
排列 如果之前存在两行的键,则打印该行减去数组中的值

0.9
-0.6786
-0.6778
0.7902
4.2099
1.0866
1.769
1.4565
因为在肯特的回答中,有人问过他

perl -ne '$a{$.}=$_;print $_-$a{$.-2}.(eof()?"\n":",") if $a{$.-2}' file

0.9,-0.6786,-0.6778,0.7902,4.2099,1.0866,1.769,1.4565
佩里狗

perl -ne '$a{$.}=$_;print $_-$a{$.-2}."\n" if $a{$.-2}' file
排列 如果之前存在两行的键,则打印该行减去数组中的值

0.9
-0.6786
-0.6778
0.7902
4.2099
1.0866
1.769
1.4565
因为在肯特的回答中,有人问过他

perl -ne '$a{$.}=$_;print $_-$a{$.-2}.(eof()?"\n":",") if $a{$.-2}' file

0.9,-0.6786,-0.6778,0.7902,4.2099,1.0866,1.769,1.4565
有了awk,我会写作

awk -v ORS="" '
    {a=b; b=c; c=$0}                  # remember the last 3 lines
    NR >= 3 {print sep c-a; sep=","}  # print the difference
    END {print "\n"}                  # optional, add a trailing newline.
' file
或者让浆糊来做繁重的工作

awk '{a=b;b=c;c=$0} NR >= 3 {print c-a}' file | paste -sd,
有了awk,我会写作

awk -v ORS="" '
    {a=b; b=c; c=$0}                  # remember the last 3 lines
    NR >= 3 {print sep c-a; sep=","}  # print the difference
    END {print "\n"}                  # optional, add a trailing newline.
' file
或者让浆糊来做繁重的工作

awk '{a=b;b=c;c=$0} NR >= 3 {print c-a}' file | paste -sd,

谢谢@Kent…如果我想将这些数据保存在一行而不是一列中,并用逗号(,)分隔,你怎么做?更新3?
paste-d-@Kent我稍后检查更新2,现在我的孩子慢慢来:)谢谢,我查一下later@kent我已经检查了updated2,它工作得很好!你能解释一下命令吗?如果你能的话,我会很感激的。@EnricAgudPique它保存数组中的所有行,并进行数学计算。对于输出,printf将让你控制你想要的输出格式。谢谢@Kent…如果我想将这些数据保存在一行不在列中,用逗号分隔(,)怎么做?update3?
paste-d-@kent我稍后检查update2,现在我的孩子慢慢来:)谢谢,我查一下later@kent我已经检查了updated2,它工作得很好!你能解释一下命令吗?如果可以的话,我会很感激的。@EnricAgudPique它保存数组中的所有行,并进行数学计算。对于输出,printf将让你控制想要的输出格式。