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:


should be split into the following lines:


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?


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

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;
  • +1 It works if you tweak the numbers. – l0b0 Jun 11 '12 at 14:55
  • Just out of curiosity, why should it be >76 in the if line? – lgarzo Jun 11 '12 at 15:11
  • Because sed sees the \r at the end of the line, which should not be counted towards the character count. – l0b0 Jun 13 '12 at 11:10
  • Eh, good point. I did not try to feed back the output. – lgarzo Jun 13 '12 at 11:15

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.