awk 条件在 bash while 循环中

Awk conditional inside bash while loop

我正在尝试制作一个逐行遍历文本文件的 while 循环,使用 Awk 测试字段是否为空,然后根据该条件是真还是假执行操作。

输入文件是这样的:

$ cat testarr.csv
cilantro,lamb,oranges
basil,,pears
sage,chicken,apples
oregano,,bananas
tumeric,turkey,plums
pepper,,guavas
allspice,goose,mangos

我的预期输出是:

this_is_one_iteration
ItIsNotBlank
this_is_one_iteration
ItIsBlank
this_is_one_iteration
ItIsNotBlank
this_is_one_iteration
ItIsBlank
this_is_one_iteration
ItIsNotBlank
this_is_one_iteration
ItIsBlank
this_is_one_iteration
ItIsNotBlank

基于 Using 'if' within a 'while' loop in Bash 和类似的线程,我这样做了:

#!/bin/bash

error=ItIsBlank
success=ItIsNotBlank
while read LINE; do
echo this_is_one_iteration
QZ1=$(awk -F "," '{print (!)}')
if [[ $QZ1==0 ]] ; then
    echo $error
else
    echo $success
fi
done < testarr.csv

这给了我:

$ bash testloop.sh
this_is_one_iteration
ItIsBlank

所以它似乎甚至没有遍历文件。但是,如果我去掉条件,它会很好地迭代。

#!/bin/bash

error=ItIsBlank
success=ItIsNotBlank
while read LINE; do
echo this_is_one_iteration
done < testarr.csv

给出:

$ bash testloop.sh
this_is_one_iteration
this_is_one_iteration
this_is_one_iteration
this_is_one_iteration
this_is_one_iteration
this_is_one_iteration
this_is_one_iteration

此外,条件似乎在不使用 awk 时工作正常:

QZ1=test
while read LINE; do
echo this_is_one_iteration
if [[ $QZ1=="test" ]] ; then
    echo It_worked
fi
done < testarr.csv

给我:

$ bash testloop.sh
this_is_one_iteration
It_worked
this_is_one_iteration
It_worked
this_is_one_iteration
It_worked
this_is_one_iteration
It_worked
this_is_one_iteration
It_worked
this_is_one_iteration
It_worked
this_is_one_iteration
It_worked

tests whether a field is blank using Awk

我想,它可以通过单个 awk 进程来实现:

awk -F, '{ print "this_is_one_iteration"; f="Not"; 
           for(i=1;i<=NF;i++) if($i=="") { f="";break }; printf "ItIs%sBlank\n",f }' testarr.csv

输出:

this_is_one_iteration
ItIsNotBlank
this_is_one_iteration
ItIsBlank
this_is_one_iteration
ItIsNotBlank
this_is_one_iteration
ItIsBlank
this_is_one_iteration
ItIsNotBlank
this_is_one_iteration
ItIsBlank
this_is_one_iteration
ItIsNotBlank

除了一个小错误外,您的脚本是正确的。添加 echo $LINE 并将其通过管道传递给 awk 语句。您脚本中的 Awk 没有可处理的输入。

#!/bin/bash 

error=ItIsBlank
success=ItIsNotBlank
while read LINE; do
echo this_is_one_iteration
QZ1=$(echo $LINE|awk -F "," '{print (!)}')
if [[ $QZ1 -eq 0 ]] ; then
 echo $error
else
 echo $success 
fi
done < testarr.csv

当我 运行 脚本现在:

[ec2-user@ip check]$ ./script.sh
this_is_one_iteration
ItIsBlank
this_is_one_iteration
ItIsBlank
this_is_one_iteration
ItIsBlank
this_is_one_iteration 
ItIsBlank
this_is_one_iteration
ItIsBlank
this_is_one_iteration
ItIsBlank
this_is_one_iteration
ItIsBlank

希望这能解决您的问题。