key value : awk

Input file:

x=1
y=2
z=5

Is it possible using awk or anything to get the following output?

key=x|y|z
value=1|2|5

I can use two separate code lines using awk or cut (with tr) to get the key and value separately, was wondering if this can be done with some awk code at a once.

Thanks

Something like this?

awk -F = '{ key[++i] = $1; value = $2 }
END {
  printf "key"; sep="="; for (j=1; j<=i; ++j) { printf ("%s%s", sep, key[j]); sep="|" }; printf "\n";
  printf "value"; sep="="; for (j=1; j<=i; ++j) { printf ("%s%s", sep, value[j]); sep="|" }; printf "\n";
}' file

If NR is defined in the END block in your variant of awk, you can replace the variable i with NR (and of course incrementing it is then done implicitly).

Thank you era. Ya this worked

Or:
(use nawk or /usr/xpg4/bin/awk on Solaris)

awk -F= 'END { printf "keys=%s\nvalues=%s\n", k, v }
{ k = k ? k s $1 : $1; v = v ? v s $2 : $2 }
' s="|" file

The same with perl:

perl -F"=" -lane'
  $k.=$F[0]."|";
  $v.=$F[1]."|";
  END {
    chop($k,$v);  
    printf "keys=%s\nvalues=%s\n",$k,$v
	}'  file

Or how about

perl -F= -lane 'push @k, shift @F; push @v, @F;
END { print "keys=", join ("|", @k), "\nvalues=", join ("|", @v) }' file

Nice :slight_smile:

With zsh:

zsh-4.3.4% printf "keys=%s\nvalues=%s\n" ${(j:|:)$(<file)%\=*} ${(j:|:)$(<file)#*=}
keys=x|y|z
values=1|2|5