한 열의 모든 요소를 ​​다른 열의 모든 요소로 나누는 방법은 무엇입니까?

한 열의 모든 요소를 ​​다른 열의 모든 요소로 나누는 방법은 무엇입니까?

파일에 두 개의 열이 있습니다.

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

관련 정보