在列中列印多行變數

在列中列印多行變數

我有一個從叢集收集值的腳本。在某些情況下,這些值有多行。我有一個 printf 格式,指定如何放置數據,但是,它沒有考慮多行,因此間距是傾斜的。

The data should look like this:

Service Group          AutoStart List          System List
foo                    sys1                    sys1
                       sys2                    sys2

相反,它看起來像這樣

Service Group          AutoStart List          System List
foo                    sys1                    
sys2                    sys1
sys2

自動啟動清單和系統清單應該是相同的,但不管怎樣,我還沒有弄清楚如何強制將值放入正確的列中。

sgheader="\n\033[4m\033[1m%-30s %-30s %-15s\033[0m\033[0m"
sgformat="\n%-30s %-30s %-15s"



printf "${sgheader}" "Service Group" "Autostart List" "System List" 
printf "${sgformat}" "${svcgroup}" "${autostrtlist}" "${hosts}"

答案1

也許是這樣的:

svcgroup='foo' autostrtlist=$'sys1\nsys2' hosts=$'sys1\nsys2'
paste <(printf '%s\n' "$svcgroup") \
      <(printf '%s\n' "$autostrtlist") \
      <(printf '%s\n' "$hosts") | expand -t30

(ksh93/zsh/bash 語法)。或者,POSIXly,在具有以下功能的系統上/dev/fd/x

paste /dev/fd/3 3<<E3 /dev/fd/4 4<<E4 /dev/fd/5 5<<E5 | expand -t 30
$svcgroup
E3
$autostrtlist
E4
$hosts
E5

除了dash,yash以及最新版本的bash,它使用臨時檔案而不是由子 shell 提供的管道,因此可能更有效率(除了更便攜之外)。

答案2

您可以從變數中刪除任何新行。

var=$(echo "$var" | tr -d '\n')

答案3

如果它們每次都適合一條線,那麼這些都是一些簡單的方法。如果您想要按照您要求的方式進行操作,則需要付出更多努力才能使列正確排列。這是基本思想:

#!/bin/bash

inputA="foo"
inputB=$'sys1\nsys2\n'
inputC=$'sys1\nsys2\n'

sgheader="\033[4m\033[1m%-30s %-30s %-15s\033[0m\033[0m\n"
sgformat="%-30s %-30s %-15s\n"

printf "${sgheader}" "Service Group" "Autostart List" "System List"

# This shows two simple ways to do this which use concatenation but
# require that the result still fit in the same space as is used for
# a single line
columnA="$inputA"
columnB=$(echo "$inputB"|awk '{printf("%s,",$0)}'|sed 's/,.\s*$//')
columnC=$(echo "$inputC"|tr '\n' ',')

printf "${sgformat}" "${columnA}" "${columnB}" "${columnC}"

# This is a version which outputs like originally asked. It is much harder
# to tweak the formatting of this version though.
pr -tm <(printf '%s\n' "$inputA") <(printf '%s\n' "$inputB") \
       <(printf '%s\n' "$inputC") | expand -t10

據我所知,按照您想要的方式執行此操作的最佳方法是混亂的。即使在那之後,您可能還想進一步細化輸出以正確排列。

相關內容