
사람이 읽을 수 있도록 편집한 Python 사전 텍스트가 있다고 가정해 보겠습니다. 이제 다음 입력과 같이 한 줄씩 표시됩니다.
입력
{"case":"0901","emailed":"yes","vote":1,"accepted":"no"},
{"case":"0908","emailed":"yes","vote":8,1"accepted":"yes"},
{"case":"0911","emailed":"no","vote":10,1"accepted":"yes"},
{"case":"0090","emailed":"yes","vote":3,1"accepted":"no"},
** 이전 형식의 모든 텍스트 파일 **
yes
그래서 나는 첫 번째와 no
두 번째를 포함하는 라인을 grep하고 싶습니다.
그래서 출력이 다음과 같을 것으로 기대합니다
산출
{"case":"0901","emailed":"yes","vote":1,"accepted":"no"},
{"case":"0090","emailed":"yes","vote":3,1"accepted":"no"},
아직 단어 순서대로 grep하는 방법을 찾을 수 없습니다.
그리고 두 번째 질문은 내 결과에 관한 것입니까?
awk
sum
총 투표수를 계산하는 기능을 사용할 수 있나요 ? 이는 4,1
출력에서 나와야 합니다 .
답변1
이것을 확인하세요:
필요한 라인 인쇄
awk -F'[,:]' '
$4 ~ "yes" && $8 ~ "no" {
print;
}' input.txt
산출
{"case":"0901","emailed":"yes","vote":1,"accepted":"no"},
{"case":"0090","emailed":"yes","vote":3,1"accepted":"no"},
합계 계산
awk -F'[,:]' '
$4 ~ "yes" && $8 ~ "no" {
sum += $6"."$7;
}
END {
print sum;
}' input.txt
산출
4.1
답변2
Python 사전 텍스트가 있습니다.
적절한파이썬사전 복구/처리:
내 메시지는 다음과 같습니다. Python은 Python입니다. 데이터 구조를 왜곡해서는 안 됩니다.
recover_dict.py
스크립트:
import sys, re, ast
with open(sys.argv[1], 'r') as f:
items = ast.literal_eval(re.sub(r"(\d+),(\d+)", "\\1.\\2,", f.read().replace('\n','')))
sum = 0
for d in items:
if d['emailed'] == 'yes' and d['accepted'] == 'no':
sum += d['vote']
print(d)
print(sum)
용법:
python recover_dict.py file
출력:
{'case': '0901', 'vote': 1, 'accepted': 'no', 'emailed': 'yes'}
{'case': '0090', 'vote': 3.1, 'accepted': 'no', 'emailed': 'yes'}
4.1
답변3
다음과 같은 것
grep 'yes.*no' yourfile \
| sed -e 's/.*vote":\([0-9,]\+\).*/\1/g' -e 's/,/./g' \
| paste -sd+ | bc
당신을 위해 일해야합니다.
설명
grep 'yes.*no' yourfile
단어 순서를 기준으로 하고 싶지만 grep
그 사이에 무엇이 있는지 모르는 경우 .*
공백이 아닌 문자를 0번 이상 반복하는 데 사용하세요. 출력(입력 파일 포함):
$ grep 'yes.*no' inputfile
{"case":"0901","emailed":"yes","vote":1,"accepted":"no"},
{"case":"0090","emailed":"yes","vote":3,1"accepted":"no"}
sed -e 's/.*vote":\([0-9,]\+\).*/\1/g' -e 's/,/./g'
위 의 출력에서 ,
앞에 이 있는 경우 숫자(숫자 및 )를 일치 시키고 로 대체합니다 . 출력...vote":
grep
,
.
$ grep 'yes.*no' inputfile | sed -e 's/.*vote":\([0-9,]\+\).*/\1/g' -e 's/,/./g'
1.
3.1
paste -sd+
숫자 사이의 개행 문자를 +
,로 대체하면 다음과 같이 출력됩니다.
$ grep 'yes.*no' inputfile | sed -e 's/.*vote":\([0-9,]\+\).*/\1/g' -e 's/,/./g' | paste -sd+
1.+3.1
bc
위의 작업( 1.+3.1
)을 실행하고 다음을 출력합니다.
$ grep 'yes.*no' inputfile | sed -e 's/.*vote":\([0-9,]\+\).*/\1/g' -e 's/,/./g' | paste -sd+ | bc
4.1