我在一个文件中有两列:
1 2
3 5
4 8
9 18
3 5
4 19
我想将第一列的每个元素划分为第二列的每个元素,并且也想打印该数字。例如:
1,2,1/2,
1,5,1/5,
1,8,1/8,
1,18,1/18,
1,19,1/19,
3,5,3/5,
4,19,4/19,
3,2,3/2,
3,5,3/8,
3,19,3/19 and so on...
请帮助我我该如何继续?
答案1
GNU 并行
parallel echo "{1},{2}" :::: <(cut -d' ' -f1 file) :::: <(cut -d' ' -f2 file) |
awk -F, '{ print $1,$2,$1"/"$2,$1/$2 }' OFS=, OFMT='%.2g'
输出:
1,2,1/2,0.5
1,5,1/5,0.2
1,8,1/8,0.12
1,18,1/18,0.056
1,5,1/5,0.2
1,19,1/19,0.053
3,2,3/2,1.5
3,5,3/5,0.6
3,8,3/8,0.38
3,18,3/18,0.17
3,5,3/5,0.6
3,19,3/19,0.16
4,2,4/2,2
4,5,4/5,0.8
4,8,4/8,0.5
4,18,4/18,0.22
4,5,4/5,0.8
4,19,4/19,0.21
9,2,9/2,4.5
9,5,9/5,1.8
9,8,9/8,1.1
9,18,9/18,0.5
9,5,9/5,1.8
9,19,9/19,0.47
3,2,3/2,1.5
3,5,3/5,0.6
3,8,3/8,0.38
3,18,3/18,0.17
3,5,3/5,0.6
3,19,3/19,0.16
4,2,4/2,2
4,5,4/5,0.8
4,8,4/8,0.5
4,18,4/18,0.22
4,5,4/5,0.8
4,19,4/19,0.21
答案2
此 bash 脚本片段读取一个名为您的问题中格式化的文本文件numbers.txt
,并输出一个 CSV,用冒号分隔,每行格式如下:
Dividend;divisor;fraction;decimal
对于小数计算,它使用工具bc
。
#!/bin/bash
declare -a Dividend Divisor
while read -r Line; do
if [ -n "$Line" ]; then
Dividends+=("${Line%% *}")
s="${Line#* }"
Divisors+=("${s%% *}")
fi
done < test.txt
for dividend in "${Dividends[@]}"; do
for divisor in "${Divisors[@]}"; do
echo "$dividend;$divisor;$dividend/$divisor;$(bc <<<"scale=5; $dividend/$divisor")"
done
done
它是如何工作的?
它将整个文件读入两个数组Dividends
,并Divisors
在嵌套循环中迭代它们(完整笛卡尔积)。这样,每个被除数就除以每个除数。
答案3
蟒蛇3
rows = open("file.txt", "r").read().split("\n")
for r in rows[:-1]:
r = r.split(" ")
print("%s,%s,%s/%s,%.2f" % (r[0], r[1], r[0], r[1], int(r[0])/int(r[1])))
为了文件.txt:
1 2
3 5
4 8
9 18
3 5
4 19
你会得到:
1,2,1/2,0.50
3,5,3/5,0.60
4,8,4/8,0.50
9,18,9/18,0.50
3,5,3/5,0.60
4,19,4/19,0.21
答案4
使用 bash 大括号扩展和 awk
c1="{$(cut -d' ' -f1 file | paste -sd,)}"
c2="{$(cut -d' ' -f2 file | paste -sd,)}"
echo echo $c1,$c2 |
bash |
tr ' ' '\n' |
awk -F, '{ print $0, $1"/"$2, $1/$2 }' OFS=, OFMT='%.2g'
输出:
1,2,1/2,0.5
1,5,1/5,0.2
1,8,1/8,0.12
1,18,1/18,0.056
1,5,1/5,0.2
1,19,1/19,0.053
3,2,3/2,1.5
3,5,3/5,0.6
3,8,3/8,0.38
3,18,3/18,0.17
3,5,3/5,0.6
3,19,3/19,0.16
4,2,4/2,2
4,5,4/5,0.8
4,8,4/8,0.5
4,18,4/18,0.22
4,5,4/5,0.8
4,19,4/19,0.21
9,2,9/2,4.5
9,5,9/5,1.8
9,8,9/8,1.1
9,18,9/18,0.5
9,5,9/5,1.8
9,19,9/19,0.47
3,2,3/2,1.5
3,5,3/5,0.6
3,8,3/8,0.38
3,18,3/18,0.17
3,5,3/5,0.6
3,19,3/19,0.16
4,2,4/2,2
4,5,4/5,0.8
4,8,4/8,0.5
4,18,4/18,0.22
4,5,4/5,0.8
4,19,4/19,0.21