2008-11-06 93 views
2

試圖從2個正確對齊的不同變量中打印出值列表。Unix C Shell腳本printf幫助

foreach finalList ($correctList $wrongList) 
printf "%20s%s\n" $finalList 
end 

這將它們打印出來,它們是對齊的,但它是一個接一個。我將如何通過每個列表中的每個項目,然後去一個新的行?

我想他們最終會出現這樣的:

Correct Incorrect 
Good1  Bad1 
Good2  Bad2 
Good3  Bad3 

好來自correctList 壞來自wrongList

擺脫\ n使得這樣的:

Good1  Bad1 Good2 Bad2 

我只想要2列。

+0

你可以根據需要給出一個佈局,對每個列表中的項目使用correct1,correct2和wrong1 wrong2等? – Svante 2008-11-06 00:37:22

回答

5

您可以在同一時間這樣遍歷兩個列表:

# Get the max index of the smallest list 
set maxIndex = $#correctList 
if ($#wrongList < $#correctList) then 
    set maxIndex = $#wrongList 
endif 

set index = 1 
while ($index <= $maxIndex) 
    printf "%-20s %s\n" "$correctList[$index]" "$wrongList[$index]" 
    @ index++ 
end 
+0

建議 - 適用於使用類似printf符號的所有語言 - 是使用「%-20s%S \ n」(或「%-19s%S \ n」如果第二欄應在塔21通常需要啓動)。這確保即使第一個字符長於20(或19)個字符,兩個值之間也有一個空格。 – 2008-11-06 01:06:02

0

嘗試擺脫\ n個

+0

然後他們只是打印所有。它結束了:好1壞1好2壞2 – Doug 2008-11-06 00:48:40

+0

@射線:這錯過了問題的重點。 – 2008-11-06 01:03:29

0

相信PR(1)命令和-m選項將幫助做你想做的事。查看其手冊頁以消除標題/預告片選項並設置列寬。

此外,我建議你不要使用C-Shell編寫腳本;你會發現sh-syntax shell(sh,bash,ksh等)更加一致並且更容易調試。