使用粘贴和数组进行列格式分离

问题描述 投票:0回答:1

此脚本使用 bash。我试图通过收集信息并使用粘贴输出它们来显示磁盘的值。有时,单个物理卷可能被分配给多个逻辑卷。使用粘贴时的输出有点奇怪。

这是我创建的函数。

function ShowVolumeAttr()
{
    local lun_id="$1"

    # Show info on PV, VG, and LV
    PV=$(pvscan | grep $lun_id | awk '{print $2}')
    VG=$(pvscan | grep $lun_id | awk '{print $4}')
    declare -a LV
    for pv in $PV
    do
        LV[${#LV[@]}]+=$(pvdisplay -m $pv | grep "Logical volume" | awk '{print $3}')
    done
    echo -e "Physical Volume(s)\tVolume Group\tLogical Volume(s)"
    echo -e "------------------\t------------\t-----------------"
    paste <(printf %s "$PV") <(printf "\t%s" "$VG") <(printf "\t%s" "${LV[@]}")
}

这是输出的样子。我希望将所有逻辑卷条目排列在彼此下方,但由于数组中第一个条目之后的每个条目都有自己的行,并且前面没有 PV/VG,因此它通常从左侧进行选项卡边。有什么办法可以排起来吗

Physical Volume(s)      Volume Group    Logical Volume(s)
------------------      ------------    -----------------
/dev/sda2               rhel            /dev/rhel/root
                /dev/rhel/var
                /dev/rhel/home
                /dev/rhel/swap
                /dev/rhel/usr
                /dev/rhel/tmp
                /dev/rhel/opt
                /dev/rhel/var

谢谢,

帕特里克

也尝试使用不同的 printf 命令将它们分开。还尝试将制表符添加到最后一个 printf 条目。

bash rhel
1个回答
0
投票

您可以尝试使用

column
而不是
paste
。类似于以下内容:

#!/bin/bash

pv="/dev/sda2"
vg="rhel"
declare -a lv
lv=(/dev/rhel/root /dev/rhel/var /dev/rhel/home /dev/rhel/swap /dev/rhel/usr /dev/rhel/tmp /dev/rhel/opt /dev/rhel/var)

for i in "${!lv[@]}"; do
  if [ "$i" -eq 0 ] ; then
    printf "%s\t%s\t%s\n" "Physical Volume(s)" "Volume Group" "Logical Volume(s)"
    printf "%s\t%s\t%s\n" "------------------" "------------" "-----------------"
  fi
  if [ "$i" -ne 0 ] ; then
    pv=" "; vg=" "
  fi
  printf "%s\t%s\t%s\t\n" "$pv" "$vg" "${lv[$i]}"
done | column -ts $'\t'

输出结果:

Physical Volume(s)  Volume Group  Logical Volume(s)
------------------  ------------  -----------------
/dev/sda2           rhel          /dev/rhel/root
                                  /dev/rhel/var
                                  /dev/rhel/home
                                  /dev/rhel/swap
                                  /dev/rhel/usr
                                  /dev/rhel/tmp
                                  /dev/rhel/opt
                                  /dev/rhel/var
© www.soinside.com 2019 - 2024. All rights reserved.