使用满足条件的变量在 bash 脚本中创建子集
·
问题:使用满足条件的变量在 bash 脚本中创建子集
我正在处理以下数据集(可以在下面找到一个示例),我想创建一个 bash 脚本,它允许我只选择满足一组条件的记录,并且满足这些条件的所有记录都收集在另一个文件中。
1.Third column must be greater than 3
2.Fouth column must be grater than 3.5
3.Second column must be 8
40462186,177827,7671,4395,190,4.31,0.42
2872296,273870,3492,95349,1216,1.27,9.41
45236699,265691,6874,5873,152,2.58,0.57
77481,40024,153,516565,1975,0.38,51.54
如果您能帮助我完成它,我将不胜感激。
先感谢您
解答
-
不能在 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的记录只满足与所示期望输出相反的条件。
更多推荐
所有评论(0)