我想做一個逐行掃描文本文件的while循環,使用awk測試一個字段是否空白,然後根據這個條件是true還是false來做一個動作。awk有條件的內部bash while循環
輸入文件是這樣的:
$ 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'命令中做到這一點? – Inian
我不在乎。我只需要測試一個字段是否是空白的,然後根據它來做bash的東西。爲什麼它不能將awk的輸出傳遞給bash? – Thoughtcraft
_proper_行是3個字段,不正確的行少於3個? – Inian