views:

1396

answers:

4

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.

+4  A: 

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
Kristian
works like a charm, thanks
rangalo
no need for cat.
ghostdog74
Fails if the file contains a '~' character
William Pursell
Removed the cat and the "~" problem...
Kristian
This inserts a newline after *every* 20 characters (per line of the original). If the original contains no newlines and you want a newline after only the first 20 characters, leave out the "g" (global) at the end. If you want this and the original contains newlines, you'll have to use a different solution.
Dennis Williamson
+1  A: 

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
ghostdog74
A: 

Append an empty line after a line with exactly 42 characters

sed -ie '/^.\{42\}$/a\
' huge_text_file
Chen Levy
A: 

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 -0777 -pe 's/(.{'$N'})/\1\n/sg' input

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

William Pursell