【发布时间】:2018-03-20 23:30:44
【问题描述】:
我正在尝试创建一个 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 (!$2)}')
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
【问题讨论】:
-
所以您想在
bash脚本或Awk命令中执行此操作? -
我不在乎。我只需要测试一个字段是否为空白,然后根据它做 bash 的东西。为什么将 awk 的输出传递给 bash 不起作用?
-
proper 行有 3 个字段,不正确的字段少于 3 个?
-
不一定,尽管在这个特定的例子中,这恰好是真的。所以不,简单地测试行中的字段数量对我没有帮助。
标签: bash if-statement awk while-loop conditional