我有一个格式为`foo =“的字符串是第一个”foo1 =“是第二个”foo3 =“是第三个”和许多字段如上述模式。我想解析这个并将o / p作为
foo foo1 foo3
is a first one is a second one is a third one
非常感谢任何帮助。
答案 0 :(得分:2)
将输出列化是困难的部分。 (我同意Noufal在这里说perl是一个很好的方法。)但是,它可以用其他更基本的工具。例如:
$ cat input foo is a first one foo1 is a second one foo3 is a third one $ ( awk 'NR % 2' input; awk 'NR % 2 == 0' input ) | paste - - - | column -s' ' -t foo foo1 foo3 is a first one is a second one is a third one
(请注意,列的-s参数应包含单引号之间的选项卡。)
答案 1 :(得分:1)
awk完全可以进行字符串解析。
s='foo="is a first one" foo1="is a second one" foo3="is a third one"'
echo $s | awk 'BEGIN{
FS="\042 "
}
{
c=NF
for(i=1;i<=NF;i++){
m = split($i , a, "=")
header[i] = a[1]
content[i]= a[2]
}
}
END{
for(i=1;i<=c;i++){
printf "%s\t", header[i]
}
print ""
for(i=1;i<=c;i++){
printf "%s\t", content[i]
}
print ""
}
'
答案 2 :(得分:0)
这是你想要的吗?
sed -nr 's/" /"\n/g;s/=/\n/gp' <<END
> foo="is a first one" foo1="is a second one" foo3="is a third one"
> END
foo
"is a first one"
foo1
"is a second one"
foo3
"is a third one"
答案 3 :(得分:0)
从William's answer窃取使用column
,这会接受OP建议的输入。它要求根据样本输入双引号:
s='foo="is a first one" foo1="is a second one" foo3="is a third one"'
echo "$s" | awk -F'"' '
{
for (i=1; i<=NF; i+=2) {
sub(/^[[:space:]]*/, "", $i)
sub(/=$/, "", $i)
vars=vars $i "\t"
}
for (i=2; i<=NF; i+=2) {vals=vals $i "\t"}
}
END {print vars; print vals}
' | column -t -s $'\t'
输出
foo foo1 foo3
is a first one is a second one is a third one