bash - parsing a file with a column of key/value pairs -
i trying parse tab delimited file last column has variable number of key-value pairs separated semicolon. here example
ab cd ef as=2;sd=5;df=12.3 gh ij kl sd=23;df=55 mn op qr as=24;df=77
i want print 2nd column , value associated key "sd" expected output should be
cd 5 ij 23
can in bash?
the problem here key-value column has variable no of entries target key have different positions in different rows.
i can grep values of given key
grep -o 'sd=[^;]*' file.txt
but can not print other column values @ same time
awk
rescue!
$ awk -v k="sd=" '{n=split($nf,a,";"); for(i=1;i<=n;i++) if(a[i]~k) {sub(k,$2" ",a[i]); print a[i]}}' file cd 5 ij 23
if key not fixed length anchoring on left better idea. change a[i]~k
a[i]~"^"k
Comments
Post a Comment