How to insert newline characters every N chars into a long string

The venerable fold command ("written by Bill Joy on June 28, 1977") can wrap lines:

$ printf "foobarzot\n" | fold -w 3
foo
bar
zot

However, there are some edge cases

BUGS Traditional roff(7) output semantics, implemented both by GNU nroff and by mandoc(1), only uses a single backspace for backing up the previous character, even for double-width characters. The fold backspace semantics required by POSIX mishandles such backspace-encoded sequences, breaking lines early. The fmt(1) utility provides similar functionality and does not suffer from that problem, but isn't standardized by POSIX.

so if your input has backspace characters you may need to filter or remove those

$ printf "a\bc\bd\be\n" | col -b | fold -w 1
e
$ printf "a\bc\bd\be\n" | tr -d "\b" | fold -w 1
a
c
d
e

I like the fold answer but just in case you want with sed, here it is:

sed 's/.\{20\}/&\
/g' filename

You can use -i for in-place insertion.


If you have the contents in a variable, such as:

var=$(head -n 50 /dev/urandom | tr -dc A-Za-z0-9)

Then you could use a bash loop over the length of the variable in chunks of 20, printing out each chunk:

for((start=1;start < ${#var}; start += 20)); do printf '%s\n' "${var:start:20}"; done

If you want them as individual variables, consider assigning the output to an array:

readarray -t passwords < <(for((start=1;start < ${#var}; start += 20)); do printf '%s\n' "${var:start:20}"; done)