我正在處理以下資料集(可以在下面找到一個示例),我想創建一個 bash 腳本,它允許我只選擇滿足一組條件的記錄,并且滿足這些條件的所有記錄都收集在另一個檔案中。
1. Regex to get which continent must be Asia, Africa or Europe, therefore discarding the rest.
2. Regex to get "Death Percentatge" must be greater than 0.50
3- Regex to get the "Survival Percentatge" to be greater than 2.00.
It is important that it is a bash script that uses these regular expressions in if conditions.
Country,Other names,ISO 3166-1 alpha-3 CODE,Population,Continent,Total Cases,Total Deaths,Tot Cases//1M pop,Tot Deaths/1M pop,Death percentage, Survival Percentage
Afghanistan,Afghanistan,AFG,40462186,Asia,177827,7671,4395,190,4.31,0.42
Albania,Albania,ALB,2872296,Europe,273870,3492,95349,1216,1.27,9.41
Algeria,Algeria,DZA,45236699,Africa,265691,6874,5873,152,2.58,0.57
Andorra,Andorra,AND,77481,Europe,40024,153,516565,1975,0.38,51.54
由于這些記錄包含在新檔案中,因此必須減去“生存百分比”和“死亡百分比”以創建一個名為“Dif.porc.pts”的新變數,以收集絕對值的百分比差異。
我提出的代碼如下,但我沒有使用其他語言的 bash 經驗。
read
while IFS=, read _ _ _ Continent _ _ _ _ _ Death Percentatge Survival Percentatge; do
if [[Continent ~ /Africa|Asia|Europe/) && (Death Percentage ~ /[0].[5-9][0-9] &&(Survival
Percentage ~ /[2-9].[0-9][0-9]]]
diff.porc.pts=$($Survical Percentatge/$Death Percentatge)|sed 's/-//'
paste -sd > new_file.txt
fi
cat new_file.txt
我還附上了所需輸出的示例。
Country,Other names,ISO 3166-1 alpha-3 CODE,Population,Continent,Total Cases,Total Deaths,Tot Cases//1M pop,Tot Deaths/1M pop,Death percentage, Survival Percentage, diff.porc.pts
Afghanistan,Afghanistan,AFG,40462186,Asia,177827,7671,4395,190,4.31,0.42,3.89
Albania,Albania,ALB,2872296,Europe,273870,3492,95349,1216,1.27,9.41,8.14
Algeria,Algeria,DZA,45236699,Africa,265691,6874,5873,152,2.58,0.57,2.01
Andorra,Andorra,AND,77481,Europe,40024,153,516565,1975,0.38,51.54,51.16
如果您能幫助我完成它,我將不勝感激。
先感謝您
uj5u.com熱心網友回復:
- 您不能在 bash 變數名中包含空格。
- 你拼錯
Percentage了Percentatge。 - 您誤解了 的列位置
Continent。 - bash 中的正則運算式運算子是
=~,不是~。 - 您不應該用斜杠將正則運算式括起來。
- 您將需要使用
bc或其他外部命令來進行十進制數的算術計算。
那么請您嘗試以下方法:
#!/bin/bash
while read -r line; do
if (( nr == 0 )); then # header line
echo "$line,diff.porc.pts"
else # body
IFS=, read _ _ _ _ Continent _ _ _ _ pDeath pSurvival <<< "$line"
if [[ $Continent =~ ^(Africa|Asia|Europe)$ && $pDeath =~ ^(0\.[5-9]|[1-9]) && $pSurvival =~ ^([2-9]\.|[1-9][0-9]) ]]; then
diff=$(echo "$pSurvival - $pDeath" | bc)
echo "$line,$diff"
fi
fi
done < input_file.txt > new_file.txt
輸出:
Country,Other names,ISO 3166-1 alpha-3 CODE,Population,Continent,Total Cases,Total Deaths,Tot Cases//1M pop,Tot Deaths/1M pop,Death percentage, Survival Percentage,diff.porc.pts
Albania,Albania,ALB,2872296,Europe,273870,3492,95349,1216,1.27,9.41,8.14
它看起來Albania只滿足與顯示的所需輸出相反的條件。
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/480609.html
