Red*_*son 3 linux shell bash sed awk
我正在尝试使用awkbash 脚本中的语句从(例如 1 或 4 和 2 或 3)文本文件中查找某些特定值。如果在文件中(在awk语句内)找到该值,那么我想从awk语句外部调用一个函数并将找到的值作为参数传递给它。
我的问题:(1)这可能吗?如果是,那么如何?(2)如果不可能或者有更好的方法,那怎么办?
请注意,我在搜索文件时跳过了文本文件的前两行。我正在使用 GNU AWK。如果需要进一步解释,请告诉我。
**我提前为交叉帖子道歉,但我没有得到我正在寻找的答案。
文件.txt
Name Col1 Col2 Col3
-----------------------
row1 1 4 7
row2 2 5 8
row3 3 6 9
Run Code Online (Sandbox Code Playgroud)
实际retrieve功能比这个简化的例子复杂得多。所以我需要调用这个函数,因为我不想把它放在awk语句中。
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
Run Code Online (Sandbox Code Playgroud)
这样做的一种丑陋方式(即根据来自 的输出在 shell 中调用函数awk)可能如下所示:
awk -F '\t' '
FNR < 2 {next}
FNR == NR {
for (i=2; i <= NF; i++) {
if (($i == 1) || ($i == 4))
printf "retrieve %s\n", $i
if (($i == 2) || ($i == 2))
printf "retrieve2 %s\n", $i
}
}
' file.txt | while read l; do eval $l; done
Run Code Online (Sandbox Code Playgroud)
然而,这在某些情况下可能会严重适得其反。
| 归档时间: |
|
| 查看次数: |
760 次 |
| 最近记录: |