Sunday, June 22, 2008

Extract key value using awk in bash


Input file:

$ cat keyval.txt
Geo=Asia
Sub=Awk
Pt=7.8


Output required:


keys=Geo|Sub|Pt val=Asia|Awk|7.8



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


.

2 comments:

Michael said...

hacky, but it works
rawdata[1]="hey"
rawdata[30]="yo"

j=1;
for val in ${rawdata[@]}; do
key=`echo ${!rawdata[@]} | cut -d" " -f${j}`

echo $key $val

let j=j+1
done





1 hey
2 yo

Karan Bohra said...

This can be accomplished many ways:

## bash
while IFS== read -r key value
do
set -- "${1-keys=}${1:+|}${key}" "${2-val=}${2:+|}${value}"
done < keyval.txt
echo ${1+"$@"}


## Sed
sed -n '
1{x;s/.*/keys val/;x}
H;g
1s/^\([^ ]*\) \([^ ]*\)\n\([^=]*\)=\(.*\)/\1=\3 \2=\4/
1!s/^\([^ ]*\) \([^ ]*\)\n\([^=]*\)=\(.*\)/\1|\3 \2|\4/
$p;h
' < keyval.txt


## Perl
perl -l -0777ne '
my %h = /^(.*)=(.*)$/gm;
print "keys=", join("|", keys %h), " values=", join("|", values %h);
' < keyval.txt


## Dc
dc -e "
# load up the main stack
$(< keyval.txt sed 's/\(.*\)=\(.*\)/[\1] [\2]/;G;h;$!d')
[[ ]n]sf
[[|]n]sg
[z2/:Xn z 2 >f z 2 !>g z 2 !>d]sd
[lk;Xn lk 2 >f lk 2 !>g lk1-sk lk 1 !>e]se
[keys=]n
z2/sk
ldx
[values=]n
lex
[]p
"

© Jadu Saikia www.UNIXCL.com