我有一个字符串格式问题,虽然我知道我想做什么,但我不确定具体如何做。我希望这里的某个地方可以提供帮助。我的问题看起来像这样:
在我的脚本中,我使用函数来编写日志输出,该输出使用标准化但可变的长度、 header 和用户定义的消息正文。消息的长度和终端宽度意味着消息经常会回绕。我想要做的是在换行中插入“填充”,以便消息在日志中显示得更加格式化。
这是我的部分工作代码的改编且未经测试的摘录。它显示了我想做的事情:
local __mgs_hdr="[${__DATE}@${__TIME} ${__script}] -> "
local __msg_body="${1}"
local __hdrlen=$(expr length $__msg_hdr)
local __msglen=$(expr length $__msg_body)
local __max_msglen=$(expr 80 - $__hdrlen)
local __line=""
if [ $__msglen -gt $__max_mslen ]; then # we need to format the message
# Insert newline followed by "$__hdrlen" whitespaces into $__msq_body at $_hdrlen intervals
# to align/justify log lines as blocks of text for each log header entry
# Replace the : with a command to format $__line
:
else
__line="${__msg_hdr}${__msg_body}"
fi
所以,我有一种方法来确定何时填充日志行,并且我认为 sed 可以做到这一点。我只是不知道怎么办。如果有人能指出我正确的方向,我将不胜感激。
这是使用静态格式生成的示例输出。它显示了我想要达到的目标:
[2012-12-27@15:56:43 test.sh] -> Writing a log file entry that
is wrapped onto the next line
with appropriate formatting...
我希望这能让我想要实现的目标更加清晰。行长度与 80 个字符的终端不匹配,但该示例具有说明性。
最佳答案
如果脚本名称是_a_really_long_name.sh,会发生什么?
[2012-12-27@15:56:43 is_a_really_long_name.sh] -> Writing a lo
g file entry
that is wrapp
ed onto the n
ext line with
appropriate f
ormatting...
如果您关心格式,那么为什么不将标题放在一行上,并将日志消息格式化在其下面的行上
[2012-12-27@15:56:43 is_a_really_long_name.sh] ->
Writing a log file entry that is wrapped onto the next line with appropriate
formatting...
一些代码 - 前者
#!/bin/bash
headerlen=40
maxlinelen=79
linelen=$maxlinelen-headerlen
spaces=" "
msg="This is a message that needs to be split into chunks that are the same width. For illustrative purpose only. Your milage mag vary."
msglen=${#msg}
start=0
while [ $start -lt $msglen ]
do
echo -n "${spaces:1:$headerlen}"
echo "${msg:$start:$linelen}"
let start=$start+$linelen
done
如果您想执行后者,那么您可以使用类似的方法来拆分消息
#!/bin/bash
linelen=10
msg="This is a message that needs to be split into chunks that are the same width. For illustrative purpose only. Your milage mag vary."
msglen=${#msg}
start=0
while [ $start -lt $msglen ]
do
echo "${msg:$start:$linelen}"
let start=$start+$linelen
done
关于Bash:处理日志文件输出的格式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14056925/