【问题标题】:column, width parameter not working列,宽度参数不起作用
【发布时间】:2017-06-23 19:28:07
【问题描述】:

我正在与column -Vcolumn from util-linux 2.23.2 一起运行 REHL7

我的 csv 文件包含一些带有长字符串的列。 我想将 csv 视为表格,并限制列宽,因为我是 通常对抽查长字符串不感兴趣。

cat foo_bar.csv | column -s"," -t -c5

似乎列宽不限于 10 个字符。 我想知道这是一个错误,还是我做错了并且看不到它?

测试输入,test.csv

co1,col2,col3,col4,col5
1,2,3,longLineOfTextThatIdoNotWantToInspectAndWouldLikeToLimit,5

运行我认为正确的命令:

cat test.csv | column -s"," -t -c5 

co1  col2  col3  col4 col5
1    2     3     longLineOfTextThatIdoNotWantToInspectAndWouldLikeToLimit  5

【问题讨论】:

    标签: linux shell unix awk multiple-columns


    【解决方案1】:

    −c−−columns 选项不会像您认为的那样做。默认, column 查看所有行以找到最长的行。如果column 可以容纳 2 个 那些宽度为 80 的线,然后每 2 行适合一个:

    $ cat file
    1 this is a short line
    2 this is a short line
    3 this line needs to be 39 or less char
    4 this line needs to be 39 or less char
    
    $ column file
    1 this is a short line                  3 this line needs to be 39 or less char
    2 this is a short line                  4 this line needs to be 39 or less char
    
    $ column -x file
    1 this is a short line                  2 this is a short line
    3 this line needs to be 39 or less char 4 this line needs to be 39 or less char
    

    如果您将-c 设置为低于 80,那么您获得的可能性会降低 超过 1 列:

    $ column -c70 file
    1 this is a short line
    2 this is a short line
    3 this line needs to be 39 or less char
    4 this line needs to be 39 or less char
    

    所以,简单地说,column 不能做你想做的事。 awk 可以这样做:

    BEGIN {
      FS = ","
    }
    {
      for (x = 1; x <= NF; x++) {
        printf "%s%s", substr($x, 1, 5), x == NF ? "\n" : "\t"
      }
    }
    

    结果:

    co1     col2    col3    col4    col5
    1       2       3       longL   5
    

    【讨论】:

    • 你是怎么知道的……?手册页很简陋。很棒的答案。
    【解决方案2】:

    我正在寻找类似问题的解决方案(截断 docker ps 输出中的列)。我不想使用 awk,而是使用 sed 解决了它。

    在本例中,我将 docker ps 的输出限制为每列 30 个字符。

    docker ps -a --format "table {{.ID}},{{.Names}},{{.Image}},{{.State}},{{.Networks}}" | \ sed "s/\([^,]\{30\}\)[^,]*/\1/g" | \ 列 -s "," -t

    该模式匹配一​​组中的 30 个非分隔符 ([^,]) 字符,然后是其余的非分隔符字符(如果该列少于 30 个字符,则它不匹配并被单独保留) .替换只是 30 个字符的组,其余列被丢弃。

    为了好玩,您还可以在列中间截断,以防列两端都有有用的信息。

    docker ps -a --format "table {{.ID}},{{.Names}},{{.Image}},{{.State}},{{.Networks}}" | \ sed "s/\([^,]\{14\}\)[^,]*\([^,]\{14\}\)/\1..\2/g" | \ 列 -s "," -t

    【讨论】:

      猜你喜欢
      • 2011-01-18
      • 1970-01-01
      • 1970-01-01
      • 2014-11-01
      • 2023-03-29
      • 2015-06-01
      • 2018-03-03
      • 2012-07-27
      • 2012-10-25
      相关资源
      最近更新 更多