在文件中我有一个包含10个元素的数字的列。我想从第3个数字中减去第1个,从第4个减去第2个,从第5个减去第3个,从第6个减去第4个,依此类推到第10个第8个。
例如:
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
答案 0 :(得分:4)
$ 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 'NF>1{print $1-$2}' <(paste <(sed -n '3,$p' file) file)
0.9
-0.6786
-0.6778
0.7902
4.2099
1.0866
1.769
1.4565
kent$ awk '{a[NR]=0+$0}END{for(i=3;i<=NR;i++)
printf "%s%s", a[i]-a[i-2],NR==i?RS:","}' file
0.9,-0.6786,-0.6778,0.7902,4.2099,1.0866,1.769,1.4565
答案 1 :(得分:1)
#!/bin/bash
#Create an array
mapfile -t lines < inputFile
output=()
for index in "${!lines[@]}"; do
# Check if the index + 2 exist
if [[ ${lines[$(expr $index + 2)]} ]]; then
#It does exist, do the math
output+=("$(expr ${lines[$index]} + ${lines[$(expr $index + 2)]})")
fi
done
printf "%s\n" "${output[@]}" > output
答案 2 :(得分:1)
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
像Kents回答中的要求一样连续
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
答案 3 :(得分:0)
用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
或者让粘贴做gruntwork
awk '{a=b;b=c;c=$0} NR >= 3 {print c-a}' file | paste -sd,