[英]calculate distance; substract the first column of the second line from the second column of the fist line using awk
I have a question. 我有个问题。 I have a file with coordinates (
TAB
separated) 我有一个坐标文件(
TAB
分隔)
2 10
35 50
90 200
400 10000
...
I would like to substract the first column of the second line from the second column of the fist line , ie calculate the distance, ie I would like a file with 我想从第一行的第二列减去第二行的第一列,即计算距离,即我想要一个带有
25
40
200
...
How could I do that using awk??? 我怎么能用awk做到这一点??? Thank you very much in advance
提前非常感谢你
here is an awk one-liner may help you: 这是一个awk单线可能会帮助您:
kent$ awk 'a{print $1-a}{a=$2}' file
25
40
200
Here's a pure bash solution: 这是一个纯bash解决方案:
{
read _ ps
while read f s; do
echo $((f-ps))
((ps=s))
done
} < input_file
This only works if you have (small) integers, as it uses bash's arithmetic. 这仅在具有(小)整数的情况下有效,因为它使用bash的算法。 If you want to deal with arbitrary sized integers or floats, you can use
bc
(with only one fork): 如果要处理任意大小的整数或浮点数,则可以使用
bc
(仅使用一个fork):
{
read _ ps
while read f s; do
printf '%s-%s\n' "$f" "$ps"
ps=$s
done
} < input_file | bc
Now I leave the others give an awk answer! 现在我离开别人给一个可怕的答案!
Alright, since nobody wants to upvote my answer, here's a really funny solution that uses bash and bc
: 好吧,既然没人愿意支持我的答案,那么这是一个使用bash和
bc
的非常有趣的解决方案:
a=( $(<input_file) )
printf -- '-(%s)+(%s);\n' "${a[@]:1:${#a[@]}-2}" | bc
or the same with dc
(shorter but doesn't work with negative numbers): 或与
dc
相同(较短,但不适用于负数):
a=( $(<input_file) )
printf '%s %sr-pc' "${a[@]:1:${#a[@]}-2}" | dc
using sed and ksh for evaluation 使用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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.