简体   繁体   中英

Bash script how to get the hostnamectl ouput in columns

i wrote the following bash script

#!/bin/bash
serverlist=server_list.txt

for server in `cat $serverlist`
 do
out="hostnamectl | egrep 'Kernel|Server|hostname';who -b"
ssh -q $server $out

and I get the following output ~

Static hostname: mshost25 
 Operating System: Red Hat Enterprise Linux Server 7.9 (Maipo)
 Kernel: Linux 3.10.0-1160.31.1.el7.x86_64
 system boot  2021-06-24 11:42

I would like the output to be in columns

Static hostname    Operating System             Kernel:                             sytem boot
 mypc1               Linux Server 7.9        Linux 3.10.0-1160.31.1.el7.x86_64    2021-06-24 11:33

here is my attempt to print in columns and worked for me. Can you try this code and inform me?

I treated your output as output.txt;

$ cat output.txt 
Static hostname: mshost25 
 Operating System: Red Hat Enterprise Linux Server 7.9 (Maipo)
 Kernel: Linux 3.10.0-1160.31.1.el7.x86_64
 system boot  2021-06-24 11:42

here is the code;

sed 's/boot/boot:/' output.txt | awk -F": " '
    { 
        for (i=1; i<=NF; i++)  {a[NR,i] = $i}
    }
    NF>p { p = NF }
    END { for(j=1; j<=p; j++) {
            str=a[1,j]
            for(i=2; i<=NR; i++) {str=str"\t\t"a[i,j];} print str}
    }' | column -s $'\t' -t

my output for this code;

Static hostname     Operating System                               Kernel                               system boot
mshost25           Red Hat Enterprise Linux Server 7.9 (Maipo)    Linux 3.10.0-1160.31.1.el7.x86_64     2021-06-24 11:42

Code is basically consists of three section:

  1. sed part is used to add : after word boot in order to further process it as a delimiter in awk section. https://askubuntu.com/a/879323
  2. awk this is basically a copy paste from https://stackoverflow.com/a/1729980/14320738 so refer to this post.
  3. column command is used just for beautiful appearance. refer here => https://unix.stackexchange.com/a/448558/434132

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM