2017-02-12 27 views
1

我想知道使用column命令排列圖表的最佳方式是將每列而不是默認的左對齊列居中。我一直在使用column -t filename命令。如何使用「列」來居中顯示圖表?

電流輸出:

Label1  label2 
Anotherlabel label2442 
label152  label42242 
label78765 label373737737 

所需的輸出:事情是這樣的

Label1  label2 
Anotherlabel label2442 
    label152  label42242 
label78765 label373737737 

基本上,我希望它爲中心,而不是左對齊。

+0

你可能必須使用awk,python或類似的東西自己編寫它。我在這裏寫了python以獲得樂趣:https://gist.github.com/sr105/04063c756db154b5df383892c021a7fb – Harvey

回答

1

下面是一個AWK溶液:

# Collect all lines in "data", keep track of maximum width for each field 
{ 
    data[NR] = $0 
    for (i = 1; i <= NF; ++i) 
     max[i] = length($i) > max[i] ? length($i) : max[i] 
} 

END { 
    for (i = 1; i <= NR; ++i) { 
     # Split record into array "arr" 
     split(data[i], arr) 
     # Loop over array 
     for (j = 1; j <= NF; ++j) { 
      # Calculate amount of padding required 
      pad = max[j] - length(arr[j]) 
      # Print field with appropriate padding, see below 
      printf "%*s%*s%s", length(arr[j]) + int(pad/2), arr[j], \ 
           pad % 2 == 0 ? pad/2 : int(pad/2) + 1, "", \ 
           j == NF ? "" : " " 
     } 
     # Newline at end of record 
     print "" 
    } 
} 

調用這樣的:

$ awk -f centre.awk infile 
    Label1   label2 
Anotherlabel label2442 
    label152  label42242 
label78765 label373737737 

printf語句使用具有動態寬度填充:

  • 第一%*s取關懷左邊填充和數據本身:arr[j]被打印並填充到總寬度爲length(arr[j]) + int(pad/2)
  • 第二個%*s打印空字符串,左填充到所需填充總數的一半。 pad % 2 == 0 ? pad/2 : int(pad/2) + 1檢查總的填充是否是偶數,如果不是,則添加額外的空間。
  • 最後的%s打印j == NF ? "" : " ",即兩個空格,除非我們在最後一個字段。

一些較舊的awks不支持%*s語法,但格式化字符串可以組裝像在這種情況下width = 5; "%" width "s"

0

下面是一個Python程序來做你想做的事情。在bash中可能太難了,所以你需要使用自定義程序或awk腳本。基本算法:列

  • 計數數
  • [可選]確保每一行具有相同的列數
  • 弄清楚數據的最大長度爲每列
  • 打印每行中使用最大長度

#!/usr/bin/env python3 

import sys 

def column(): 
    # Read file and split each line into fields (by whitespace) 
    with open(sys.argv[1]) as f: 
     lines = [line.split() for line in f] 
    # Check that each line has the same number of fields 
    num_fields = len(lines[0]) 
    for n, line in enumerate(lines): 
     if len(line) != num_fields: 
      print('Line {} has wrong number of columns: expected {}, got {}'.format(n, num_fields, len(line))) 
      sys.exit(1) 
    # Calculate the maximum length of each field 
    max_column_widths = [0] * num_fields 
    for line in lines: 
     line_widths = (len(field) for field in line) 
     max_column_widths = [max(z) for z in zip(max_column_widths, line_widths)] 
    # Now print them centered using the max_column_widths 
    spacing = 4 
    format_spec = (' ' * spacing).join('{:^' + str(n) + '}' for n in max_column_widths) 
    for line in lines: 
     print(format_spec.format(*line)) 

if __name__ == '__main__': 
    column() 
相關問題