Shell script to print output in table format

Shell script to print output in table format

Sometimes you may need to print the output of a command, or contents of a file, or output of shell script in a tabular manner that is easy to understand. Generally, many commands provide a very congested output that is not easy to understand. In this article, we will learn how to print output in table format, that is, as columns in Linux.


Shell script to print output in table format

There are many ways to print output in column format. We will use column command for this purpose.

Using column utility

The column command allows you to transform standard output or file content into tabular manner. Let us say you have the following file data.txt

$ cat data.txt
pos|author|articles|comments
1|john|431|9785
2|jane|369|7894
3|jim|194|2349

You can easily format the above output to table form by passing the cat command’s output to column command.

$ cat data.txt  | column -t -s "|"

In the above command -t option is used to specify that output should be printed as tabular columns, and -s option is used to specify delimiter. Here is the output in tab separated manner.

pos  author         articles  comments
1    john           431       9785
2    jane           369       7894
3    jim            194       2349

By default, the column command will fill rows before columns. If you want to fill columns before rows, use -x option. If you also want to include empty lines present in input, use -e option.

If you want to save the tabular output to another file, simply use the redirection operator, followed by filename.

$ cat data.txt  | column -t -s "|" > data-table.txt
$ cat data-table.txt
pos  author         articles  comments
1    john           431       9785
2    jane           369       7894
3    jim            194       2349

You can easily add the above command in shell script as shown further. Create an empty shell script.

$ vi print-table.sh

Add the following lines to it.

#!/bin/sh

cat $1  | column -t -s $2

Save and close the file. Make it executable with the following command.

$ chmod +x print-table.sh

Now you can run the above shell script as shown below.

$ ./print-table.sh data.txt "|"

In the above command, the first argument after shell script is the input file name/path. The second argument is the delimiter present in input file. You can use the same script to split a comma separated or tab delimited file into table.

Although you can use other tools like awk, sed and cut for the above purpose, column command provides one of the easiest ways to neatly print output as table.

In this article, we have learnt how to print output in table format.

Also read:

How to Change PHP Version in Ubuntu
MySQL Clustered Index
How to Execute Stored Procedure in Python
How to Manage PostgreSQL Views
PostgreSQL Python Transaction

Leave a Reply

Your email address will not be published. Required fields are marked *