Bash Printf格式错误

时间:2016-10-05 04:12:40

标签: linux bash macos printf string-formatting

我的bash脚本我正在使用printf打印变量并格式化输出 虽然大多数列是对齐的,但有一些不是(注意:运动媒体)。以下是打印数据的代码:

for((counter = 0; counter < ${#views[@]}; counter++))
{
  printf "%-40s | %-9s | %-15s" "${users[$counter]}" "${views[$counter]}" "${duration[$counter]}" #"${ids[$counter]}" "${titles[$counter]}"
  printf "\n"
}

以下是输出示例:

users                                    | views     | duration       
Saturday Night Live                      | 10853524  | 9:46           
Right Side Broadcasting                  | 346333    | 2:34:31        
FOX 10 Phoenix                           | 319507    | 3:29           
LastWeekTonight                          | 2997140   | 19:55          
nigahiga                                 | 6372021   | 2:56           
Disney Movie Trailers                    | 7372656   | 1:50           
RWW Blog                                 | 125448    | 1:29           
POLITICAL HUMOR                          | 173517    | 4:23           
solangeknowlesmusic                      | 1613158   | 4:25           
theDOMINICshow                           | 488995    | 4:13           
TheWeekndVEVO                            | 1937027   | 3:59           
swampgarage                              | 720718    | 1:43           
Fox News                                 | 164336    | 7:40           
Bud Light                                | 224627    | 0:16           
BuzzFeedVideo                            | 5575303   | 7:56           
swampfoot                                | 8177252   | 9:07           
Bloomberg                                | 349937    | 2:33           
Kubau2                                   | 6358091   | 8:40           
DOCUMENTARY TUBE                         | 926035    | 13:12          
KLM Royal Dutch Airlines                 | 5796674   | 6:12           
DOCUMENTARY TUBE                         | 3456648   | 10:51          
ExtremeTV                                | 18846489  | 6:34           
Sport Mídia                             | 4806074   | 8:23           
Sam Chui                                 | 6124697   | 6:47           
DMKSPROD                                 | 4111882   | 11:30 

1 个答案:

答案 0 :(得分:0)

这就是发明制表符的原因:将文本放在同一位置。

$ a="ExtremeTV"
$ b="Sport Mídia"

$ printf '%18s |\n' "$a" "$b"
     ExtremeTV |
  Sport Mídia |

$ printf '%18s \t|\n' "$a" "$b"
     ExtremeTV      |
  Sport Mídia       |