2013-10-29 105 views

回答

1

這裏是一個純解決方案:

{ 
    read _ ps 
    while read f s; do 
     echo $((f-ps)) 
     ((ps=s)) 
    done 
} < input_file 

這隻能如果您有(小)整數,因爲它使用bash的算術。如果你想處理任意大小的整數或浮點數,你可以使用bc(只有一個叉):

{ 
    read _ ps 
    while read f s; do 
     printf '%s-%s\n' "$f" "$ps" 
     ps=$s 
    done 
} < input_file | bc 

現在我離開了別人給一個awk答案!


好了,因爲沒有人願意給予好評我的答案,這是一個使用bc一個非常有趣的解決方案:

a=($(<input_file)) 
printf -- '-(%s)+(%s);\n' "${a[@]:1:${#a[@]}-2}" | bc 

dc相同的(短,但不與負數工作):

a=($(<input_file)) 
printf '%s %sr-pc' "${a[@]:1:${#a[@]}-2}" | dc 
6

這裏一個awk的一行可以幫助你:

kent$ awk 'a{print $1-a}{a=$2}' file 
25 
40 
200 
+0

哇肯特。你簡化了我用awk查看的方式。謝謝 – Ashish

+0

請注意,這將只在第二列從不爲零時起作用 – user000001

+0

然後'awk'NR> 1 && $ 0 {print $ 1-a} {a = $ 2}'file'可以做到,但我想這是一個邊緣案件。 – fedorqui

1

使用SED和ksh評估

sed -n " 
1x 
1!H 
$ !b 

x 
s/^ *[0-9]\{1,\} \(.*\) [0-9]\{1,\} *\n* *$/\1/
s/\([0-9]\{1,\}\)\(\n\)\([0-9]\{1,\}\) /echo \$((\3 - \1))\2/g 
s/\n *$// 
w /tmp/Evaluate.me 
" 
. /tmp/Evaluate.me 
rm /tmp/Evaluate.me 
相關問題