bash - 使用满足条件的变量在 bash 脚本中创建一个子集

标签 bash ubuntu

我正在处理以下数据集(可以在下面找到一个示例),我想创建一个 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 变量名中包含空格。
  • 你拼错了 PercentagePercentatge .
  • 您误判了 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的记录只满足相反的条件
    显示的所需输出。

    关于bash - 使用满足条件的变量在 bash 脚本中创建一个子集,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72329258/

    相关文章:

    iphone - 编辑应用程序的 .plist 文件

    bash - 导入shell脚本函数

    ubuntu - grafana-server 在 CHDIR 步骤失败

    c - 在 Linux Mint 中编译 C 程序时出错

    mongodb - 节点应用程序无法连接到我的 ubuntu 实例上的 mongo 镜像

    bash 提示符和函数内的回显颜色

    linux - 如何找到没有软链接(soft link)的目录?

    linux - 如何在终端底部上方添加空行

    r - 安装包 ‘devtools’ 在 Ubuntu 上具有非零退出状态

    python - 以编程方式获取给定 PID 的子进程列表