Monday, February 1, 2016

AWK: Hashing Arbitrary Columns of Every Lines Using SHA-2 (SHA256) and MD5

*This code has a bug and may not work in your environment.
*This gives wrong SHA-2 or MD5 hash value.
*The echo command inside awk seems not aware of -n option.
*echo command under Bourne shell also has this behaviour.

SHA-2 (SHA256) hash every second column values in comma separated values:

awk -F, '{
cmd="echo -n \""$2"\" | openssl dgst -sha256"
while (cmd | getline line){
print line
}
close(cmd)
}' ./test.txt


MD5 (message-digest algorithm) hash every second column values in comma-separated values:

awk -F, '{
cmd="echo -n \""$2"\" | md5"
while (cmd | getline line){
print line
}
close(cmd)
}' ./test.txt