有人能给我一些代码或算法或其他东西来解决下面的问题吗?我有几个文件,每个文件都有不同的列数,例如:
$> cat file-1
1 2
$> cat file-2
1 2 3
$> cat file-3
1 2 3 4我想减去列的绝对值,并除以每一不同列的行中所有值的总和,只需一次(没有重复列对的组合):
in file-1 case I need to get:
0.3333 # because |1-2/(1+2)|
in file-2 case I need to get:
0.1666 0.1666 0.3333 # because |1-2/(1+2+3)| and |2-3/(1+2+3)| and |1-3/(1+2+3)|
in file-3 case I need to get:
0.1 0.2 0.3 0.1 0.2 0.1 # because |1-2/(1+2+3+4)| and |1-3/(1+2+3+4)| and |1-4/(1+2+3+4)| and |2-3/(1+2+3+4)| and |2-4/(1+2+3+4)| and |3-4/(1+2+3+4)|发布于 2012-01-24 07:58:17
虽然我猜你在输入数据中犯了一个小错误,但这应该是可行的。根据您的第三个模式,以下数据应该是-
而不是:
in file-2 case I need to get:
0.1666 0.1666 0.3333 # because |1-2/(1+2+3)| and |2-3/(1+2+3)| and |1-3/(1+2+3)|它应该是:
in file-2 case I need to get:
0.1666 0.3333 0.1666 # because |1-2/(1+2+3)| and |1-3/(1+2+3)| and |2-3/(1+2+3)|以下是awk one的内联代码:
awk '
NF{
a=0;
for(i=1;i<=NF;i++)
a+=$i;
for(j=1;j<=NF;j++)
{
for(k=j;k<NF;k++)
printf("%s ",-($j-$(k+1))/a)
}
print "";
next;
}1' file简短版本:
awk '
NF{for (i=1;i<=NF;i++) a+=$i;
for (j=1;j<=NF;j++){for (k=j;k<NF;k++) printf("%2.4f ",-($j-$(k+1))/a)}
print "";a=0;next;}1' file输入文件:
[jaypal:~/Temp] cat file
1 2
1 2 3
1 2 3 4测试:
[jaypal:~/Temp] awk '
NF{
a=0;
for(i=1;i<=NF;i++)
a+=$i;
for(j=1;j<=NF;j++)
{
for(k=j;k<NF;k++)
printf("%s ",-($j-$(k+1))/a)
}
print "";
next;
}1' file
0.333333
0.166667 0.333333 0.166667
0.1 0.2 0.3 0.1 0.2 0.1 来自较短版本的测试:
[jaypal:~/Temp] awk '
NF{for (i=1;i<=NF;i++) a+=$i;
for (j=1;j<=NF;j++){for (k=j;k<NF;k++) printf("%2.4f ",-($j-$(k+1))/a)}
print "";a=0;next;}1' file
0.3333
0.1667 0.3333 0.1667
0.1000 0.2000 0.3000 0.1000 0.2000 0.1000发布于 2012-01-24 08:17:25
@Jaypal也打败了我!这就是我所拥有的:
awk '{for (x=1;x<=NF;x++) sum += $x; for (i=1;i<=NF;i++) for (j=2;j<=NF;j++) if (i < j) printf ("%.1f ",-($i-$j)/sum)} END {print ""}' file.txt输出:
0.1 0.2 0.3 0.1 0.2 0.1打印到一位小数。
@Jaypal,有没有快速打印绝对值的方法?也许就像:abs(value)?
编辑:
@Jaypal,是的,我也试过搜索,但找不到简单的东西:-(似乎if ($i < 0) $i = -$i是可行的。我想你可以用sed去掉任何减号:
awk '{for (x=1;x<=NF;x++) sum += $x; for (i=1;i<=NF;i++) for (j=2;j<=NF;j++) if (i < j) printf ("%.1f ", ($i-$j)/sum)} {print ""}' file.txt | sed "s%-%%g"干杯!
发布于 2012-01-24 06:47:32
因为它看起来像家庭作业,所以我会采取相应的行动。
要查找文件中存在的总数,您可以使用
cat filename | wc -w通过以下方式查找first_number:
cat filename | cut -d " " -f 1要在文件中查找和,请执行以下操作:
cat filename | tr " " "+" | bc现在,您有了total_nos,使用如下命令:
for i in {seq 1 1 $total_nos}
do
#Find the numerator by first_number - $i
#Use the sum you got from above to get the desired value.
donehttps://stackoverflow.com/questions/8979659
复制相似问题