1

Related to How to join vCards lines, vCard does a weird kind of line splitting: If a line contains more than 75 characters, insert a "CR, LF, space" sequence. Thus the following line:

123456789A123456789B123456789C123456789D123456789E123456789F123456789G123456789H123456789I123456789J123456789K123456789L123456789M123456789N123456789O123456789P123456789Q123456789R123456789S123456789U123456789V123456789W123

should be split into the following lines:

123456789A123456789B123456789C123456789D123456789E123456789F123456789G12345
 6789H123456789I123456789J123456789K123456789L123456789M123456789N123456789
 O123456789P123456789Q123456789R123456789S123456789U123456789V123456789W123

You can't just insert the line split sequence every 75 characters, because then there would be more than 75 characters per line again, and you can't just insert after counting 75 characters because it should only be inserted if the line is longer than 75 characters. One way to do it is to repeat the following command until the input no longer changes:

sed -e 's/^\(.\{75\}\)\([^\r]\)/\1\r\n \2/' < file | sed -e '...' | ...

That's obviously not going to work with indeterminately long lines, and is horribly inefficient. How would you do this sort of replacement?

2 Answers 2

4

To your script you only need to add two commands: P (print up to the first newline) and D (delete up to the first newline and repeat if there is any text left).

sed -e '{ s/\(.\{75\}\)\(.\)/\1\n \2/; P; D }' file
0
2

This is a not-so-nice attempt to solve the problem:

#!/usr/bin/awk -f

{
    if (length($0) > 76) {
        printf("%s\r\n ", substr($0, 1, 75));
        $0 = substr($0, 76);
        while (length($0) > 74) {
            printf("%s\r\n ", substr($0, 1, 74));
            $0 = substr($0, 75);
        }
    }
    print $0;
}
4
  • +1 It works if you tweak the numbers.
    – l0b0
    Commented Jun 11, 2012 at 14:55
  • Just out of curiosity, why should it be >76 in the if line?
    – lgarzo
    Commented Jun 11, 2012 at 15:11
  • Because sed sees the \r at the end of the line, which should not be counted towards the character count.
    – l0b0
    Commented Jun 13, 2012 at 11:10
  • Eh, good point. I did not try to feed back the output.
    – lgarzo
    Commented Jun 13, 2012 at 11:15

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .