1

I have some code that prints select columns from the output of lsblk. However, the spacing in the result makes it hard to read. Is there anyway to do this while maintaining the white space?

echo "`sudo lsblk | awk -F ' ' '{print $1 "  " $4 "  " $6 "  " $7}'`"

output:

NAME  SIZE  TYPE  MOUNTPOINT
sda  238.5G  disk
├─sda5  68.6G  part  /
├─sda6  7.8G  part  [SWAP]
└─sda8  1000M  part

3 Answers3

2

One method is to use printf and assign column widths yourself:

lsblk | awk '{printf "%-8s %8s %5s %s\n",$1,$4,$6,$7}'

You may freely adjust the column widths in the printf statement to fit your needs.

Example:

$ lsblk | awk '{printf "%-8s %8s %5s %s\n",$1,$4,$6,$7}'
NAME         SIZE  TYPE MOUNTPOINT
sda        500.0G  disk 
├─sda1       100M  part /boot
├─sda2      28.6G  part /

Aside

Consider the form as shown in the question:

echo "`cmd1 | cmd2`"

versus the form:

cmd1 | cmd2

While both forms are similar, the subtle differences between these two are discussed in depth here. Usually, the later form provides fewer surprises.

John1024
  • 74,655
2

Here, you can tell lsblk to output the columns you want in the first place:

$ lsblk -o NAME,SIZE,TYPE,MOUNTPOINT
NAME                 SIZE TYPE MOUNTPOINT
sda                465.8G disk
├─sda1                 1G part
└─sda2             464.8G part
  ├─VG_XY-debian64    40G lvm  /
  ├─VG_XY-swap        16G lvm  [SWAP]
  └─VG_XY-home       300G lvm  /home
sr0                 1024M rom
0

@John1024's answer and @steeldriver's comment are perfectsolutions.

Alternatively fix the previously obtained output

...your_command | column -t
JJoao
  • 12,170
  • 1
  • 23
  • 45
  • That would also break the device tree if it had several levels like in the example in my answer and would left-align instead of right-aligne the size (see also the MAJ:MIN column that is aligned on the colon which would complicate matters if on wanted that column included). This solution has the advantage of not hard-coding the maximum length of the device path. – Stéphane Chazelas Nov 17 '17 at 09:17