【问题标题】:Linux command to layout tab separated list nicelyLinux命令很好地布局制表符分隔列表
【发布时间】:2013-05-29 10:06:07
【问题描述】:

我想生成一个带有制表符分隔列的日志文件。它应该具有以下格式,除了注释字段之外的所有内容都带有制表符分隔的输出

time        date        alias   comment
10:09:20    03/06/13    jre     This is a test comment

我将 csh 用于历史目的

set time = `perl -MPOSIX -e 'print POSIX::strftime("%T", localtime)'`
set date = `perl -MPOSIX -e 'print POSIX::strftime("%d/%m/%y", localtime)'`
set alias = jre
set comment = "This is a test comment"

将我的文本发送到column -t

echo "time\tdate\talias\tcomment" | column -t > somefile
echo "$time\t$date\t$alias\t$comment" | column -t >> tt

我几乎得到了我想要的。但是,我的评论字段中的空格也更改为制表符。有没有办法可以用标签分隔前 3 个字段,但在 cmets 字段中保持空格分隔?

【问题讨论】:

    标签: linux perl sed awk


    【解决方案1】:

    由于您的评论位于最后一列,请尝试使用paste。例如:

    paste <(echo -e "this\tis\ttab\tseparated") <(echo "this is your comment")
    

    默认情况下,paste 也会加入制表符。

    【讨论】:

    • 感谢您的解决方案。我在 csh 中收到错误消息 Missing name for redirect,但在 bash 中没有。我认为这与无关的空白字符有关。 csh很郁闷
    • bash -c paste &lt;(echo -e "this\tis\ttab\tseparated") &lt;(echo "this is your comment") 成功了
    • 酷。很高兴你把它整理好了:-)
    【解决方案2】:

    一种选择是使用 完成所有工作:

    awk '
        BEGIN {
            OFS = "\t"
            header = "time date alias comment"
            gsub( /\s+/, OFS, header )
            print header
    
            out[0] = strftime( "%T", systime() )
            out[1] = strftime( "%d/%m/%y", systime() )
            out[2] = "jre"
            out[3] = "This is a test comment"
    
            l = length( out )
            for ( i = 0; i < l; i++ ) {
                printf "%s%s", out[ i ], i == l ? "" : OFS;
            }
            printf "\n"
        }
    '
    

    它产生:

    time    date    alias   comment
    11:45:00    03/06/13    jre This is a test comment
    

    它不会打印在标题下方,但在这种情况下,最好使用格式化打印 (printf)。

    【讨论】:

      【解决方案3】:

      这可能对你有用:

      printf 'Time\tDate\tAlias\tComment\n' > file
      printf '%s\t%s\t%s\t%s\n' $(date '+%T') $(date '+%d/%m/%y') jre "This is a comment" >> file
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2023-04-07
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-07-04
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多