Reputation: 115
I have a string in the format `foo="is a first one" foo1="is a second one" foo3="is a third one" and many fields like the said pattern. I want to parse this and have o/p as
foo foo1 foo3
is a first one is a second one is a third one
Any help is greatly appreciated.
Upvotes: 2
Views: 1945
Reputation: 246764
Stealing the use of column
from William's answer, this accepts the OP's suggested input. It requires the values to be double-quoted as per the sample input:
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'
outputs
foo foo1 foo3
is a first one is a second one is a third one
Upvotes: 0
Reputation: 342313
Awk is perfectly fine to do string parsing.
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 ""
}
'
Upvotes: 1
Reputation: 212228
Columnizing the output is the hard part. (I would agree with Noufal here that perl is a good way to go.) However, it is doable with other more basic tools. For example:
$ 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
(Note that the -s argument to column should contain a tab between the single quotes.)
Upvotes: 2
Reputation: 51
Is this you wanted ?
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"
Upvotes: 0