dbain
dbain

Reputation: 71

Shell Script output formatting

I have output from a shell script like below

output1        ..... 1
output2     ..... 2
output3                 ............3

I tried to format it with equal spacing inside script but output still not have uniform spacing.

I want to print the output like below.

output1         ..... 1
output2         ..... 2
output3         ......3

Are there any commnads available to get this done. I use bash.

here is the code.

lnode=abc
printf "server name                     ......... "$lnode""
printf "\nserver uptime and load details :                                                         ......... `uptime`"
printf "\n"
lcpu=`cat /proc/cpuinfo  | grep -i process |wc -l`
printf "Total number of CPUs on this server :                                       .........  $lcpu\n"

-Thanks.

Upvotes: 1

Views: 10098

Answers (1)

John1024
John1024

Reputation: 113964

The idea of printf is that you specify a format string that specifies column widths, etc:

$ cat script.sh
lnode=abc
printf "%-40s %s\n" "server name :"  ".........  $lnode"
printf "%-40s %s\n" "server uptime and load details :"   "......... `uptime`"
lcpu=$(cat /proc/cpuinfo  | grep -i process |wc -l)
printf "%-40s %s\n" "Total number of CPUs on this server :"    ".........  $lcpu"

The first directive in the format string, %-40s, is applied to the first argument that follows the format string. It tells printf to display that argument in a 40-character-wide column. If we had used %40s, it would be a right-aligned column. I specified %-40s so that it would be left-aligned.

This produces output like:

$ bash script.sh
server name :                            .........  abc
server uptime and load details :         .........  18:05:50 up 17 days, 20 users,  load average: 0.05, 0.20, 0.33
Total number of CPUs on this server :    .........  4

Documentation

Bash's printf command is similar to printf in other languages, particularly the C version. Details specific to bash are found in man bash. Detailed information about the available format options is found in man 3 printf. To begin, however, you are probably better served by a tutorial such as this one or this one or this one.

Upvotes: 5

Related Questions