Awk Fun!

Awk is a powerful toy linux users have. As explained in wiki

The AWK language is a data-driven scripting language consisting of a set of actions to be taken against streams of textual data – either run directly on files or used as part of a pipeline – for purposes of extracting or transforming text, such as producing formatted reports.

Lately, I have seen some entries in Linkedin that sentences are in binary form like that:

As a funny work, I used awk to easily transform them into human readable sentences. You may find the file here in github and the content is:

BEGIN{
	FS=" "
	result=""
} 

{
	for(i=1;i<NF;i++){ total=0 chr="" # print "Order:" i " Binary Number:" $i; split($i,arr,"") for(j=8;j>0;j--){
			subtotal = arr[j]*(2^(8-j));
#			print "Binary:"arr[j] " Exponent:" 2^(8-j) " Result:" subtotal;
			total += subtotal;
		}
		chr=sprintf("%c",total)
#		print "Total:" total " Character:" chr "\n";
		result= result chr;
	}	
}

END{
	print "\n\n" result;
}

In some cases, there were no space between octets. Therefore, an extra step had to be done, parse input according to modulus 8. The new code is something like that more or less (github):

BEGIN{
	FS=""
	str=""
}

{
	for(i=1;i<NF;i++){
		if(i%8==0){
			str1=str1 $i;
			str=str str1 " ";
			str1="";
		}else{
			str1= str1 $i;
		}
	}
} 

END{
	print str;
}

As a result, save source text to a file called source.txt (you may also use echo or cat or sth else to use in pipeline). Save first code as resolve.awk and run it:

awk -f resolve.awk source.txt

If there is no space in source, then save second code as put_space.awk and run it:

awk -f put_space.awk source.txt|awk -f resolve.awk
Advertisements