如何以固定长度块打印可变长度行?
我需要分析(使用grep
)并打印(使用一些格式)一个文件的内容 应用程序的日志。
该日志包含可变长度行的文本数据。我需要的是,经过一些 grep 后,循环输出的每一行并以最大固定长度 50 个字符打印它。如果一行超过 50 个字符,它应该打印一个换行符,然后继续下一行的其余部分,依此类推,直到该行完成。
我尝试使用 printf 来执行此操作,但它不起作用,我不知道为什么。尽管 \t
字符(制表符)有效,但它只是以与 echo
相同的方式输出行,而不考虑 printf
格式。
function printContext
{
str="$1"
log="$2"
tmp="/tmp/deluge/$$"
rm -f $tmp
echo ""
echo -e "\tLog entries for $str :"
ln=$(grep -F "$str" "$log" &> "$tmp" ; cat "$tmp" | wc -l)
if [ $ln -gt 0 ];
then
while read line
do
printf "\t%50s\n" "$line"
done < $tmp
fi
}
怎么了?我知道我可以创建一个子字符串例程来完成此任务,但是 printf
对于这样的事情应该很方便。
I need to to analyze (with grep
) and print (with some formatting) the content of an
app's log.
This log contains text data in variable length lines. What I need is, after some grepping, loop each line of this output and print it with a maximum fixed length of 50 characters. If a line is longer than 50 chars, it should print a newline and then continue with the rest in the following line and so on until the line is completed.
I tried to use printf
to do this, but it's not working and I don't know why. It just outputs the lines in same fashion of echo
, without any consideration about printf
formatting, though the \t
character (tab) works.
function printContext
{
str="$1"
log="$2"
tmp="/tmp/deluge/$"
rm -f $tmp
echo ""
echo -e "\tLog entries for $str :"
ln=$(grep -F "$str" "$log" &> "$tmp" ; cat "$tmp" | wc -l)
if [ $ln -gt 0 ];
then
while read line
do
printf "\t%50s\n" "$line"
done < $tmp
fi
}
What's wrong? I Know that I can make a substring routine to accomplish this task, but printf
should be handy for stuff like this.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
而不是:
用于
将行截断为仅 50 个字符。
Instead of:
use
to truncate your line to 50 characters only.
我不确定 printf,但看到 perl 是如何安装在任何地方的,一个简单的 1 行怎么样?
I'm not sure about printf but seeing as how perl is installed everywhere, how about a simple 1 liner?
这是一种仅使用 bash 的笨拙方法,可将字符串分成 50 个字符的块
Here's a clunky bash-only way to break the string into 50-character chunks