Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Convert CSV Boolean-enumerations to bitfield in bash

In bash (>=3) Given a line from a csv file such as:

arbitrary descriptor, uid, PASS, FAIL, NA, PASS, PASS, CLEAR

I want to compute 00100110b as a result. The pattern here being that the PASS columns become 1’s in a bit field. The result above is equivalent to 0x26 or 38 decimal.

My attempt was initially to echo into awk, however, not sure how to test <$whatever_number>. Assuming this approach I suppose a pattern match result would output to a ternary print statement for 1 or 0. Then maybe xxd to go from ASCII to binary.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

something like(?):

echo "arbitrary descriptor, uid, PASS, FAIL, NA, PASS, PASS, CLEAR" | awk -F',' '{??? ~ /\s*PASS\s*/ ? print "1" : print "0"}' |  xxd -b

A second approach using sed also didn’t quite get there:

echo "arbitrary descriptor, uid, PASS, FAIL, NA, PASS, PASS, CLEAR" | sed 's/,\s*PASS\s*/1/g'| sed 's/[^1]*?,/0/g  |  xxd -b

ideas?

>Solution :

Using any awk:

$ awk -F' *, *' -v OFS= '{for (i=1; i<=NF; i++) $i=($i=="PASS")} 1' file
00100110
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading