Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

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?

share|improve this question
add comment

2 Answers 2

up vote 4 down vote accepted

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
share|improve this answer
    
Excellent, thanks! –  l0b0 Jun 11 '12 at 14:56
add comment

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;
}
share|improve this answer
    
+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
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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