输入文件的每一行中都有不同数量的字段。
有什么办法可以通过awk获得预期的输出?
awk -F',' '{print "echo "$1; for (i = 2; i <= NF; i++) print "command1 "$i " command2"}' test.txt
test.txt
"abc",4,21,22,25
"standard",1
"test",4,5,10,11,12
输出:
echo "abc"
command1 4 command2
command1 21 command2
command1 22 command2
command1 25 command2
echo "standard"
command1 1 command2
echo "test"
command1 4 command2
command1 5 command2
command1 10 command2
command1 11 command2
command1 12 command2
预期输出:
echo "abc" command1 4 command2
echo "abc" command1 21 command2
echo "abc" command1 22 command2
echo "abc" command1 25 command2
echo "standard" command1 1 command2
echo "test" command1 4 command2
echo "test" command1 5 command2
echo "test" command1 10 command2
echo "test" command1 11 command2
echo "test" command1 12 command2
答案 0 :(得分:1)
请尝试以下操作:
awk -F, '{for (i=2;i<=NF;i++) print "echo", $1, "command1", $i, "command2"}'
例如:
$ cat file
"abc",4,21,22,25
"standard",1
"test",4,5,10,11,12
$ awk -F, '{for (i=2;i<=NF;i++) print "echo", $1, "command1", $i, "command2"}' file
echo "abc" command1 4 command2
echo "abc" command1 21 command2
echo "abc" command1 22 command2
echo "abc" command1 25 command2
echo "standard" command1 1 command2
echo "test" command1 4 command2
echo "test" command1 5 command2
echo "test" command1 10 command2
echo "test" command1 11 command2
echo "test" command1 12 command2
默认OFS
是空格,所以我只用逗号分隔需要打印的不同内容。
有趣的是,GNU sed
解决方案:
sed -r '/,/!d;/,/{s/([^,]*),([^,]*)/"echo" \1 "command1" \2 "command2"\n\1/; P; D;}'
另一种类似于RavinderSingh13's answer的noloop awk
方法,但简洁明了:
awk -F, '{gsub(/,/,"\necho " $1 " command1 ");sub(/[^\n]*\n/,"");gsub(/\n|$/," command2\n");printf $0}' file
答案 1 :(得分:1)
这里没有使用循环的另一种方法。
awk -F, '
/^\"/ && prev{
print prev
prev=""
}
{
gsub(/,/,"\necho " $1 " command1 ")
}
{
gsub(/$/," command2")
prev=$0
sub(/.*\"\n/,"",prev)
gsub(/\n/," command2\n",prev)
}
END{
if(prev){
print prev
}
}' Input_file
输出如下。
echo "abc" command1 4 command2
echo "abc" command1 21 command2
echo "abc" command1 22 command2
echo "abc" command1 25 command2
echo "standard" command1 1 command2
echo "test" command1 4 command2
echo "test" command1 5 command2
echo "test" command1 10 command2
echo "test" command1 11 command2
echo "test" command1 12 command2
答案 2 :(得分:0)
只需将echo语句放入for循环内
$ awk -F',' '{for (i = 2; i <= NF; i++) print "echo "$1 " command1 "$i " command2"}' test.txt
echo "abc" command1 4 command2
echo "abc" command1 21 command2
echo "abc" command1 22 command2
echo "abc" command1 25 command2
echo "standard" command1 1 command2
echo "test" command1 4 command2
echo "test" command1 5 command2
echo "test" command1 10 command2
echo "test" command1 11 command2
echo "test" command1 12 command2
$