gpt4 book ai didi

linux - 如何在shell脚本生成的文件顶部写标题

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:20:21 30 4
gpt4 key购买 nike

我有一个 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

非常感谢任何线索。

最佳答案

尝试以下操作:

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 并不重要> - 在任一情况下,文件都被附加到。)

关于linux - 如何在shell脚本生成的文件顶部写标题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22800766/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com