bash - passing a parameter in awk command won't work -


i run script bellow ./command script.sh 11, first line of code bellow stores output (321) in parameter x (checked echo on line 2). on line 3 try use parameter x retrieve last 2 columns on lines value in first column equal x (in doc2.csv). won't work when replace z=$x z=321it works fine. why won't code work when passing parameter?

#!/bin/bash x="$(awk -v y=$1  -f\; '$1 == y' ~/documents/doc1.csv | cut -d ';' -f2)" echo $x awk -v z=$x -f, '$1 == z' ~/documents/doc2.csv | cut -d ',' -f2,3 

doc1.csv (all columns have unique values)

33;987 22;654 11;321 ... 

doc2.csv

321,156843,abcd 321,637253,hyeb 123,256843,bhjn 412,486522,hdbc 412,257843,bhjn 862,256843,bhln ... 

like others have mentioned there characters coming along ride in field 2 of cut command.

if use awk print column want instead of entire line , cutting shouldn't have problems. if still need dos2unix.

n=33; x=$(awk -v y=$n  -f\; '$1 == y {print $2}' d1); echo ${x}; awk -v z=$x -f, '$1 == z' d2 

d1 , d2 contain doc1 , doc2 contents outlined.

as can see did stop using cut on output of awk , told awk print second field if first field equal input variable.

by way awk pretty powerful if weren't aware... can entire program within awk.

n=11; awk -v x=$n -f\; 'nr==fnr{ if($1==x){ y[$2]; } next}  $1 in y{print $2, $3}' d1 <( sed 's/,/;/g' d2) 

nr==fnr trick says "if still in first file, this"... key not forgetting use next skip rest of awk command. once second file fnr flips 1 nr keeps incrementing they'll never equal again.

so first file load second column values array first column matches our passed variable. optimize since said d1 unique lines.

so once next file logic skips , runs $1 in y. checks if first column in array have created. if awk prints column 2 , 3.

<( sed 's/,/;/g' d2) means want treat output of sed command file. sed command converting commas in d2 semicolons matches fs awk expects.

hopefully you've learned bit awk, read more here http://www.catonmat.net/blog/ten-awk-tips-tricks-and-pitfalls/ , great redirection cheat sheet available here http://www.catonmat.net/download/bash-redirections-cheat-sheet.pdf .


Comments

Popular posts from this blog

asynchronous - C# WinSCP .NET assembly: How to upload multiple files asynchronously -

aws api gateway - SerializationException in posting new Records via Dynamodb Proxy Service in API -

asp.net - Problems sending emails from forum -