我正在尝试使用awk
bash脚本中的语句从文本文件(例如1或4和2或3)中查找一些特定值。如果在文件中(awk
语句内)找到了该值,那么我想从awk
语句外调用一个函数,并将找到的值作为参数传递给它。
我的问题:(1)这可能吗?如果是这样,那又如何?(2)如果不可能或有更好的方法,那怎么办?
请注意,搜索文件时,我跳过了文本文件的前两行。让我知道是否需要进一步说明。
file.txt
Name Col1 Col2 Col3
-----------------------
row1 1 4 7
row2 2 5 8
row3 3 6 9
实际功能retrieve
比此简化示例复杂得多。因此,我需要对此函数进行调用,因为我不想将其放在awk
语句中。
编辑1:我正在使用GNU AWK
编辑2:如果找到2或3,可以说我还有另一个功能。那它将如何运作?
function retrieve {
if [[ "$1" == "1" ]]; then
echo "one beer on the wall"
elif [[ "$1" == "4" ]]; then
echo "four beers on the wall"
fi
}
function retrieve2 {
if [[ "$1" == "2" ]]; then
echo "two beers on the wall"
elif [[ "$1" == "3" ]]; then
echo "three beers on the wall"
fi
}
awk -F '\t' '
FNR < 2 {next}
FNR == NR {
for (i=2; i <= NF; i++)
{
if (($i == 1) || ($i == 4))
printf(%s, "'retrieve "$i" '") # Here is the problem
if (($i == 2) || ($i == 2))
printf(%s, "'retrieve2 "$i" '") # Here is the problem
}
}
' file.txt
跳过awk,以bash的方式做所有事情
tail -n +3 file.txt | while read -r ignored c1 c2 c3; do
echo "$c1"
echo "$c2"
echo "$c3"
done | while read -r value; do
if [ "$value" -eq 1 -o "$value" -eq 4 ]; then
retrieve "$value"
elif [ "$value" -eq 2 -o "$value" -eq 3 ]; then
retrieve2 "$value"
fi
done
说明
tail
跳过前两行本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句