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


Question

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.

1
28
7/27/2009 8:34:39 AM

Accepted Answer

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
42
7/27/2009 10:18:31 AM

Here is POSIX solution:

awk '{gsub(/.{5}/,"&\n")}1' file

Or:

fold -w5 file

Input:

banana strawberry grape

Output:

banan
a str
awber
ry gr
ape

Interestingly, the Awk solution is more performant than fold.


Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon