55

I'm new to awk and sed, and I'm looking for a way to truncate a line at 80 characters, but I'm printing several strings in that line using printf. The last two strings are the ones that give me problems because they vary in size on each iteration of my code. Here's my current code:

printf "%5d  %3s%.2s %4s %s %s \n" "$f" "$month" "$day" "$year" "$from" "$subject"

This code is being used to create a summary of email messages that get passed through a Bash script. What I do know, is that with the spaces and requirements of my other strings, I have room for 60 characters between the $from and $subject strings.

Any help is appreciated.

4

5 回答 5

130

我正在寻找一种方法来截断 80 个字符的行...

您可以将输出通过管道传输到cut

printf ... | cut -c 1-80

如果您想确保每行不超过 80 个字符(或换行以适应指定宽度),您可以使用fold

printf ... | fold -w 80
于 2013-11-06T05:36:53.863 回答
26

仅使用 Bash(语法:)来解决此问题的另一种方法${var:0:80},例如:

printf "%5d  %3s%.2s %4s %s %s \n" "$f" "$month" "$day" "$year" "$from" "${subject::80}"

这会在字符串到达​​之前将其截断printf。此方法还允许您为每个打印列单独指定不同的最大宽度。

于 2014-01-07T23:53:29.550 回答
2

我在尝试使用截断的目录名称自定义我的 bash 提示时遇到了同样的问题。最终奏效的是:

PS1='\u@\h:`echo $(basename $PWD) | cut -c 1-15`\$ '
于 2016-02-14T16:29:55.173 回答
1

C版怎么样?

#include <stdio.h>
int maxline = 80;
int main(int argc, char* argv[])
{
    char line[2048];
    if ((argc>1) && (atoi(argv[1]) > 0)) {
        maxline = atoi(argv[1]);
    }
    while (fgets(line, sizeof(line), stdin)) {
        line[maxline] = '\0';
        printf("%s\n", line);
    }
}
于 2013-11-06T06:05:22.760 回答
1

您可以使用 substr 仅获取 from 和 subject 的前 n 个字符,因为您知道最多只能玩 60 个字符,您可以获取 'from' 的第 25 个和 'subject' 的第 35 个。

#!/usr/bin/gawk -f
BEGIN { 
 # set ouput delimiter to comma
 OFS=","
 #  set input delimiter to bar
 FS="|"  }

{
f=$1
month=$2
day=$3
year=$4
from=$5
subject=$6
from=substr(from,1,25) 
subject=substr(subject,1,35)
printf ("%5d,%3s%.2s,%4s,%s,%s\n",f,month,day,year,from,subject)
}

在此文件上运行上述内容

12123|Jan|14|1970|jack@overthehill.com|“生日快乐” 14545|Jan|15|1970|jill@thewell.com|“希望你的头没事” 27676|Feb|14|1970|jack@overthehill .com|“今晚还有吗?” 29898|Feb|14|1970|jill@thewell.com|“当然,如果你带巧克力的话。” 34234|Feb|15|1970|jack@overthehill.com|“昨晚玩得很开心,希望你也一样。等不及周末了,爱杰克”

退货

12123,Jan14,1970,jack@overthehill.com,"Happy birthday"
14545,Jan15,1970,jill@thewell.com,"Hope your head is ok"
27676,Feb14,1970,jack@overthehill.com,"Still on for tonight?"
29898,Feb14,1970,jill@thewell.com,"Sure, if you bring the chocolate."
34234,Feb15,1970,jack@overthehill.com,"Had a great time last night, hope
于 2015-05-29T22:28:17.317 回答