如何遍历文本两列,仅在第二列含指定字符串时输出第一列
提取符合列条件的行的第一列
样本文件内容
someText here some other columns (exist but I don't intend to read them) anotherText there some other columns (exist but I don't intend to read them) YouAreGood here some other columns (exist but I don't intend to read them) HeIsNormal there some other columns (exist but I don't intend to read them)
需求
检查每行第二列是否为here,若是则将对应行的第一列输出到另一个文件,期望输出:
someText YouAreGood
现有错误脚本
#!/usr/bin/bash awk '{print $2}' sample | while read -r line do if [ "$line" == 'here' ] then echo "$line" fi done
该脚本无法正确实现需求,始终无法匹配到目标条件(或匹配后无法输出预期内容),得不到想要的结果。
问题分析
这个脚本的核心问题:
- 仅提取每行第二列进行循环判断,此时已丢失对应行的第一列信息,就算匹配成功也只能输出
here,而非需要的第一列内容 - 用管道+
while read的方式处理文本,不仅效率低,还容易因换行符、空格等细节导致匹配异常
正确解法
直接用awk完成所有逻辑,无需额外循环判断,简洁高效:
#!/usr/bin/bash awk '$2 == "here" {print $1}' sample > output.txt
逻辑说明
$2 == "here":判断当前行的第二列是否等于here{print $1}:满足条件时,输出当前行的第一列> output.txt:将结果重定向到output.txt文件中
内容的提问来源于stack exchange,提问作者Saeed
相关产品推荐
相关产品推荐

