bash 如何在固定长度的块中打印可变长度的行?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9132511/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-18 01:29:16  来源:igfitidea点击:

How to printf a variable length line in fixed length chunks?

bashprintingnewlinebreak

提问by user1187987

I need to to analyze (with grep) and print (with some formatting) the content of an app's log.

我需要分析(使用grep)并打印(使用某种格式)应用程序日志的内容。

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.

此日志包含可变长度行中的文本数据。我需要的是,在一些 grepping 之后,循环此输出的每一行并以最大固定长度 50 个字符打印它。如果一行超过 50 个字符,它应该打印一个换行符,然后在下一行继续其余的行,依此类推,直到该行完成。

I tried to use printfto 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 printfformatting, though the \tcharacter (tab) works.

我试图用来printf这样做,但它不起作用,我不知道为什么。它只是以与 相同的方式输出行echo,而不考虑printf格式,尽管\t字符(制表符)有效。

function printContext
{
    str=""
    log=""
    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 printfshould be handy for stuff like this.

怎么了?我知道我可以制作一个子字符串例程来完成这个任务,但是printf对于这样的事情应该很方便。

回答by anubhava

Instead of:

代替:

printf "\t%50s\n" "$line"

use

printf "\t%.50s\n" "$line"

to truncate your line to 50 characters only.

将您的行截断为仅 50 个字符。

回答by frankc

I'm not sure about printf but seeing as how perl is installed everywhere, how about a simple 1 liner?

我不确定 printf 但看到 perl 是如何安装的,一个简单的 1 liner 怎么样?


echo $ln | perl -ne ' while( m/.{1,50}/g ){ print "$&\n" } '

回答by glenn Hymanman

Here's a clunky bash-only way to break the string into 50-character chunks

这是将字符串分成 50 个字符的块的笨拙方法

i=0
chars=50
while [[ -n "${y:$((chars*i)):$chars}" ]]; do
  printf "\t%s\n" "${y:$((chars*i)):$chars}"
  ((i++))
done