2014-05-07 48 views
1

我可以在迴路中使用echo打印我的數組元素,但輸出格式非常糟糕。那裏我嘗試注射標籤,但只有很多元素之間的空格ssince每個元素的長度是不同的。我不知道如何使用printf?我試過了,但它不能正常工作。有沒有一種方法來格式化我的printf或回顯,因此每個元素之間有相同數量的空格?這讓我發瘋。使用printf打印沒有空白的數組元素

while [[ $counter -lt $nai ]]; 
do 
#echo ${slist[$counter]} $'\t' ${sstate[$counter]} $'\t' $'\t' ${scached[$counter]} 
printf ${slist[$counter]} $'\t' ${sstate[$counter]} $'\t' $'\t' ${scached[$counter]} 
counter=$(($counter + 1)) 
done 

總之我只想打印我的格式元素與同等數量的元件之間的空間這樣

abc cdf efg 

什麼,我得到的是

abc  cdf   efg 

謝謝

+0

也許這將幫助你:[如何從bash變量修剪空白](http://stackoverflow.com/questions/369758/how-to-trim-whitespace-from-bash-variable) – Martin

+0

@Marti n'「你的打印語句」| tr -s'''''檢查是否可行 – PradyJord

回答

1

如果要打印有N位元素在它們之間,可以使用printf:

a="foo" 
b="somestring" 
c="bar" 

# Print each argument with three spaces between them 
printf "%s " "$a" "$b" "$c" 
# Print a line feed afterwards 
printf "\n" 

這導致:

foo somestring bar 
otherdata foo bar 

您也可以使用格式%-12s墊每個元素12個字符:

# Pad each field to 12 characters 
printf "%-12s" "$a" "$b" "$c" 
printf "\n" 

結果造成:

foo   somestring bar   
otherdata foo   bar 
+0

感謝這項工作就好 – theuniverseisflat

1

嘗試使用printf格式字符串

printf "%s %s %s\n" ${slist[$counter]} ${sstate[$counter]} ${scached[$counter]} 

如果字段沒有空格,用column -t

{ 
echo my dog has fleas 
echo some random words here 
} | column -t 
my dog  has fleas 
some random words here 

或者,你的情況:while ...; do ...; done | column -t

+0

感謝它更好..有相等的間距..但由於元素長度不相同,所以它們沒有正確對齊。有沒有辦法使它們正確對齊? – theuniverseisflat

+0

答覆已更新。顯示不止一行樣本輸入會很有幫助。 –