pretty column (field) printing with awk

You know what you have to do… you have to collect all the strings for every field, keep the max length for each column, then at the end spit them back out again.

But… you need to store each field for each row and awk only supports 1 dimensional arrays… suck it up and say the script only supports up to a max of 255 fields:

BEGIN {
	row = 0
	max_fields = 0;
	super_max = 255;
} {
	for ( i = 1 ; i <= NF ; i++ ) {
		idx = row + super_max * i;
		len = length( $i );
		data[ idx ] = $i;
		if ( len > max[ i ] ) {
			max[ i ] = len;
		}
	}
	if ( NF > max_fields ) {
		max_fields= NF;
	}
	row++;
} END {
	for ( r = 0 ; r < row ; r++ ) {
		for ( i = 1 ; i <= max_fields ; i++ ) {
			idx = r + super_max * i;
			fmt = "%-" max[ i ]  "s ";
			printf( fmt , data[ idx ], max[ i ]  );
		}
		printf( "\n" );
	}
}

columnbo.awk

Here is some prettified output:

this.logger            = logger;            
this.dataSourceFactory = dataSourceFactory; 
this.wsdlUrl           = wsdlUrl;           
this.wsdlKey           = wsdlKey;           
this.documentDAO       = documentDAO;   
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: