计算 bash 中列之间的百分比?
calculate percentage between columns in bash?
我有一个包含许多列的长制表符格式的文件,我想计算两列(第 3 列和第 4 列)之间的百分比,并使用这种格式 (%46.00) 的对应编号打印此百分比。
输入:
file1 323 434 45 767 254235 275 2345 467
file1 294 584 43 7457 254565 345 235445 4635
file1 224 524 4343 12457 2542165 345 124445 41257
期望的输出:
file1 323 434(134.37%) 45(13.93%) 767 254235 275 2345 467
file1 294 584(198.64%) 43(14.63%) 7457 254565 345 235445 4635
file1 224 524(233.93%) 4343(1938.84%) 12457 2542165 345 124445 41257
我试过了:
cat test_file.txt | awk '{printf "%s (%.2f%)\n",[=13=],(/)*100}' OFS="\t" | awk '{printf "%s (%.2f%)\n",[=13=],(/)*100}' | awk '{print ,,,,,,,,,,}' - | sed 's/ (/(/g' | sed 's/ /\t/g' >out.txt
它有效,但我想要一些剪裁的东西。
我会说:
$ awk '{=sprintf("%d(%.2f%)", , (/)*100); =sprintf("%d(%.2f%)", , (/)*100)}1' file
file1 323 434(134.37%) 45(13.93%) 767 254235 275 2345 467
file1 294 584(198.64%) 43(14.63%) 7457 254565 345 235445 4635
file1 224 524(233.93%) 4343(1938.84%) 12457 2542165 345 124445 41257
具有避免口是心非的功能:
awk 'function print_nice (num1, num2) {
return sprintf("%d(%.2f%)", num1, (num1/num2)*100)
}
{=print_nice(,); =print_nice(,)}1' file
这里使用sprintf
来表达特定的格式,并存储在一个变量中。计算结果显而易见。
我有一个包含许多列的长制表符格式的文件,我想计算两列(第 3 列和第 4 列)之间的百分比,并使用这种格式 (%46.00) 的对应编号打印此百分比。
输入:
file1 323 434 45 767 254235 275 2345 467
file1 294 584 43 7457 254565 345 235445 4635
file1 224 524 4343 12457 2542165 345 124445 41257
期望的输出:
file1 323 434(134.37%) 45(13.93%) 767 254235 275 2345 467
file1 294 584(198.64%) 43(14.63%) 7457 254565 345 235445 4635
file1 224 524(233.93%) 4343(1938.84%) 12457 2542165 345 124445 41257
我试过了:
cat test_file.txt | awk '{printf "%s (%.2f%)\n",[=13=],(/)*100}' OFS="\t" | awk '{printf "%s (%.2f%)\n",[=13=],(/)*100}' | awk '{print ,,,,,,,,,,}' - | sed 's/ (/(/g' | sed 's/ /\t/g' >out.txt
它有效,但我想要一些剪裁的东西。
我会说:
$ awk '{=sprintf("%d(%.2f%)", , (/)*100); =sprintf("%d(%.2f%)", , (/)*100)}1' file
file1 323 434(134.37%) 45(13.93%) 767 254235 275 2345 467
file1 294 584(198.64%) 43(14.63%) 7457 254565 345 235445 4635
file1 224 524(233.93%) 4343(1938.84%) 12457 2542165 345 124445 41257
具有避免口是心非的功能:
awk 'function print_nice (num1, num2) {
return sprintf("%d(%.2f%)", num1, (num1/num2)*100)
}
{=print_nice(,); =print_nice(,)}1' file
这里使用sprintf
来表达特定的格式,并存储在一个变量中。计算结果显而易见。