要在shell脚本中分析字符串吗
我有一个格式为`foo=“是第一个”foo1=“是第二个”foo3=“是第三个”的字符串和许多类似于上述模式的字段。我想解析这个,并将o/p作为要在shell脚本中分析字符串吗,shell,Shell,我有一个格式为`foo=“是第一个”foo1=“是第二个”foo3=“是第三个”的字符串和许多类似于上述模式的字段。我想解析这个,并将o/p作为 foo foo1 foo3 is a first one is a second one is a third one 非常感谢您的帮助。这是您想要的吗 sed -nr 's/" /"\n/g;s/=/\n/gp' <<END > foo="is a fi
foo foo1 foo3
is a first one is a second one is a third one
非常感谢您的帮助。这是您想要的吗
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"
sed-nr的/“/”\n/g;s/=/\n/gp'结束
福
“这是第一个”
foo1
“这是第二个”
foo3
“是第三个”
将输出列化是最困难的部分。(我同意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
$cat输入
福
这是第一个
foo1
这是第二个
foo3
这是第三个
$(awk'NR%2'输入;awk'NR%2==0'输入)|粘贴-|列-s'-t
foo foo 1 foo 3
第一个是第二个是第三个
(请注意,列的-s参数应该在单引号之间包含一个制表符。)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 ""
}
'
s='foo=“是第一个”foo1=“是第二个”foo3=“是第三个”
echo$s|awk'开始{
FS=“\042”
}
{
c=NF
对于(i=1;i从中窃取列
的使用,这接受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'
你已经尝试过什么?你在哪里研究过这个任务?你遇到过什么问题吗?我用FS commadn用awk尝试过,但没有成功。因为你已经尝试了awk
,我建议你转到perl,而不是在shell中进行。这很简单。@Noufal,他可能还不够努力。awk是作为Perl进行字符串解析非常好。可能随着时间的推移,Perl在我的经验中通常比awk更有能力。非常感谢您的回复。它工作得很好。您能解释一下它的实际工作方式吗?我还希望命令读取文件中的输入。您能相应地更正它吗?如果我能以表格形式输入数据,而不是以行形式打印。很抱歉,现在回复太迟了,但我想你一定会得到更好的答案。。。
foo foo1 foo3
is a first one is a second one is a third one