awk脚本读取每行中具有不同字段数的输入文件
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了awk脚本读取每行中具有不同字段数的输入文件相关的知识,希望对你有一定的参考价值。
输入文件在每行中具有不同的字段数。
有没有办法用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
答案
这里不使用循环的另一种方法。
awk -F, '
/^"/ && prev{
print prev
prev=""
}
{
gsub(/,/,"
echo " $1 " command1 ")
}
{
gsub(/$/," command2")
prev=$0
sub(/.*"
/,"",prev)
gsub(/
/," command2
",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
另一答案
请试试这个:
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"
1/; P; D;}'
另一个类似awk
的noloop RavinderSingh13's answer方法,但简洁:
awk -F, '{gsub(/,/,"
echo " $1 " command1 ");sub(/[^
]*
/,"");gsub(/
|$/," command2
");printf $0}' file
另一答案
只需将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
$
以上是关于awk脚本读取每行中具有不同字段数的输入文件的主要内容,如果未能解决你的问题,请参考以下文章