如何在awk中将两列相乘?


8

我想将输入文件中的第1列与第2列(到文件末尾)相乘,并在单独的文件中输出1列并乘以3列。

input.txt:

1 677679866
2 121867616
3 49413198
4 40415982

output.txt:

1 677679866
2 243735232
3 148239594
4 161663928

这里有问题吗?
mikeserv

Answers:


15
awk '{ print $1, $1 * $2 }' input.txt > output.txt

4

这是一个awk解决方案:

$ awk '$0=$1" "$1*$2' input.txt 
1 677679866
2 243735232
3 148239594
4 161663928

但是您可以通过多种方式来实现,这是一种perl解决方案:

$ perl -ape 's/$F[1]/$F[0]*$F[1]/e' input.txt
1 677679866
2 243735232
3 148239594
4 161663928

您可以使用-i选项进行更改:

$ perl -i.bak -ape 's/$F[1]/$F[0]*$F[1]/e' input.txt
By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.