Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pretty print table with awk

I want to print a table that looks like this:

> field1 field2 field3 field4    
> 11.79     7.87    11.79    68   
> .. more numbers

How can I arrange it that the captions for the columns are arranged in a way that puts them on top of the respective column?

> field1    field2  field3   field4       
> 11.79     7.87    11.79    68
> .. more numbers

My generating script looks like this: capture.sh:

  echo 'field1, field2, field3, field4'
  awk '/Capture the tablestuff/{set variables}
  /DONE/ { printf("%5d %8.2f %8.2f %8.2f \n" ,field1, field2, field3, filed4); '

I really would like to refrain from ascii-formatting the echo command if I can.

like image 759
tarrasch Avatar asked Jun 07 '11 08:06

tarrasch


People also ask

How do you print a table in awk?

I.e. using BEGIN to print the header, and then print each line formatted according to the printf, with all the numbers in the input file, here assuming 4 on each line and nothing else. Tweek it to your needs... Using awk , how can we ensure that the column width will fit any arbitrary-length string?

What is awk '{ print $1 }'?

The awk is a very powerful command or interpreted scripting language to process different text or string data. The awk is generally used to process command output or text or configuration files. The awk provides '{print $1}' command in order to print the first column for the specified file or output.

What awk $0?

In awk, $0 is the whole line of arguments, whereas $1 is just the first argument in a list of arguments separated by spaces.


2 Answers

How can i arrange it that the captions for the colums are arranged in a way that puts them on top of the respective column?

Use column.

Example from the man page:

   (printf "PERM LINKS OWNER GROUP SIZE MONTH DAY HH:MM/YEAR NAME\n" \
   ; ls -l | sed 1d) | column -t
like image 168
Prince John Wesley Avatar answered Sep 19 '22 12:09

Prince John Wesley


How about this one-liner:

awk 'BEGIN {printf("%s %8s %8s %8s \n" ,"field1", "field2", "field3", "field4")}
{printf("%6.2f %8.2f %8.2f %8.2f\n", $1, $2, $3, $4)}' input

field1   field2   field3   field4 
 11.79     7.87    11.79    68.00
 11.79     7.87    11.79    68.00
 11.79     7.87    11.79    68.00
 11.79     7.87    11.79    68.00

I.e. using BEGIN to print the header, and then print each line formatted according to the printf, with all the numbers in the input file, here assuming 4 on each line and nothing else. Tweek it to your needs...

like image 25
Fredrik Pihl Avatar answered Sep 19 '22 12:09

Fredrik Pihl