【问题标题】:How to write the heading at the top of of file generated by a shell script如何在 shell 脚本生成的文件顶部写入标题
【发布时间】:2014-04-02 03:06:11
【问题描述】:

我有一个在文件中写入一些数据的 shell 脚本。我想添加一个标题"Instance Details",在打印文件中的实际数据之前应该居中对齐。

我试过这段代码:

out="Instances_$today_date"

awk -F'\t' -v of="$out" '

    # (input and other code omitted...)

    BEGIN { # Set the printf() format string for the header and the data lines.
    fmt = "%-12s %-33s %-15s %s\n"
    # Print the header
    printf("Instance Details") > of
      printf(fmt, "Instance id", "Name", "Owner", "Cost.centre") > of

}'

但执行此代码后我得到的输出:

Instance DetailsInstance id  Name                              Owner           Cost.centre

预期输出:

                              Instance Details


Instance id  Name                              Owner           Cost.centre

高度赞赏任何线索。

【问题讨论】:

  • 是什么让您期望“实例详细信息”居中显示?
  • 这实际上是文件中的标题。
  • 请继续。这是一个标题,并且...究竟应该使它居中?你能指出代码中的哪一行是造成这种情况的原因吗?
  • 问题已解决,谢谢

标签: linux shell file-io awk


【解决方案1】:

尝试以下方法:

awk -F'\t' -v of="$out" '

  # (input and other code omitted...)

  BEGIN { # Set the printf() format string for the header and the data lines.
     # Print the header
    headerText="Instance Details"
    headerMaxLen=74
    padding=(length(headerText) - headerMaxLen) / 2
    printf("%" padding "s" "%s" "%" padding "s"  "\n\n\n", "", headerText, "") > of
    fmt="%-12s %-33s %-15s %s\n"
    printf(fmt, "Instance id", "Name", "Owner", "Cost.centre") >> of
  }'
  • 通过变量of 传递输出文件的名称。
  • 计算Instance Details 任一侧的必要填充,使其在输出行居中显示(行长度源自输出的最后一行的长度)。
  • 输出 Instance Details 并带有 3 个换行符以创建所需的空行。
  • (请注意,2nd printf 语句使用 > of>> of 无关紧要 - 无论哪种情况,文件都附加到。 )

【讨论】:

  • @mklenment0:实际上我已经定义了of。请在我的脚本中多看几行
  • @MeghaSharma:好的,我已经匹配了你更新的代码;在我看来,pr() 函数与手头的问题无关,所以我没有包括它。请注意,在您的代码中,您通过使用> of 而不是>> of 来保持覆盖 输出文件of;在不向awk 输入任何内容的情况下尝试我的代码,看看它是否将所需的标头输出到of
  • @mklenment0:即使没有'>>`,我也能得到想要的输出。这是一个好习惯吗?
  • @MeghaSharma:我的立场已得到纠正:awk 中的输出重定向使得> 的多次使用针对同一输出文件追加到文件,所以在语句中other 除了写入给定文件的第一个文件,您可以交替使用>>>。但是,写入给定文件的 first 语句很重要:如果它使用 >,则首先截断现有的输出文件。
  • @MeghaSharma:您应该提供反馈以帮助本页的未来读者:如果您觉得我的回答解决了您的问题,请单击大复选标记;如果您觉得答案至少有帮助,请点击向上的大箭头进行投票。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-12-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多