AWK中的三元运算符

时间:2018-10-31 22:28:12

标签: bash awk

我正在尝试创建awk脚本以从txt文件读取数据并创建输出脚本。脚本在第1行和第3行上打印了不必要的信息。是否可以创建输出?

awk -F'[",]+' '{print "echo line " (NF>7 ? $(NF-2) " commands1 " $(NF-1) " " $2 " object " $3" object " $4 " object " $5 " object ": $(NF-2) " commands1 " $(NF-1) " " $2 " object " $3" object ") "commands2"""}' test.txt

test.txt

"b","1","program"
"c","a","d","b","2","program"
"a","3","program"
"c","a","4","program"
"a","b","5","program"

输出:

echo line 1 commands1 program b object 1 object commands2
echo line 2 commands1 program c object a object d object b object commands2
echo line 3 commands1 program a object 3 object commands2
echo line 4 commands1 program c object a object commands2
echo line 5 commands1 program a object b object commands2

预期输出:

echo line 1 commands1 program b object commands2
echo line 2 commands1 program c object a object d object b object commands2
echo line 3 commands1 program a object commands2
echo line 4 commands1 program c object a object commands2
echo line 5 commands1 program a object b object commands2

1 个答案:

答案 0 :(得分:1)

不确定主题行为何在谈论三元运算符,但这是一种执行您似乎想做的事情的方法:

$ cat tst.awk
BEGIN { FS="[\",]+" }
{
    printf "echo line %d commands1 %s", $(NF-2), $(NF-1)
    for (i=2; i<(NF-2); i++) {
        printf " %s object", $i
    }
    print " commands2"
}

$ awk -f tst.awk file
echo line 1 commands1 program b object commands2
echo line 2 commands1 program c object a object d object b object commands2
echo line 3 commands1 program a object commands2
echo line 4 commands1 program c object a object commands2
echo line 5 commands1 program a object b object commands2