How to insert a new line character after a fixed number of characters in a file

Viewed 79767

I am looking for a bash or sed script (preferably a one-liner) with which I can insert a new line character after a fixed number of characters in huge text file.

6 Answers

How about something like this? Change 20 is the number of characters before the newline, and temp.text is the file to replace in..

sed -e "s/.\{20\}/&\n/g" < temp.txt

Let N be a shell variable representing the count of characters after which you want a newline. If you want to continue the count accross lines:

perl -0xff -pe 's/(.{'$N'})/$1\n/sg' input

If you want to restart the count for each line, omit the -0xff argument.

Because I can't comment directly (to less reputations) a new hint to upper comments:

I prefer the sed command (exactly what I want) and also tested the Posix-Command fold. But there is a little difference between both commands for the original problem: If you have a flat file with n*bytes records (without any linefeed characters) and use the sed command (with bytes as number (20 in the answer of @Kristian)) you got n lines if you count with wc. If you use the fold command you only got n-1 lines with wc! This difference is sometimes important to know, if your input file doesn't contain any newline character, you got one after the last line with sed and got no one with fold

if you mean you want to insert your newline after a number of characters with respect to the whole file, eg after the 30th character in the whole file

gawk 'BEGIN{ FS=""; ch=30}
{
    for(i=1;i<=NF;i++){
        c+=1
        if (c==ch){
            print "" 
            c=0           
        }else{
            printf $i
        }
    }
    print ""
}' file

if you mean insert at specific number of characters in each line eg after every 5th character

gawk 'BEGIN{ FS=""; ch=5}
{
    print substr($0,1,ch) "\n" substr($0,ch)
}' file

Append an empty line after a line with exactly 42 characters

sed -ie '/^.\{42\}$/a\
' huge_text_file
Related