How can I split string to lines with specific width using unix commands? When the input string is infinite? How can I split string to lines with specific width using unix commands? When the input string is infinite? unix unix

How can I split string to lines with specific width using unix commands? When the input string is infinite?


fold can be your friend:

$ fold -w 80 fileHello.Hello.Hello.Hello.Hello.Hello.Hello.Hello.Hello.Hello.Hello.Hello.Hello.Hello.Hello.Hello.Hello.Hello.Hello.Hello.Hello.Hello.Hello.Hello.Hello.Hello.Hello.Hello.Hello.Hello.Hello.Hello.Hello.Hello.Hello.Hello.Hello.Hello.Hello.Hello.Hello.Hello.Hello.Hello.Hello.Hello.Hello.Hello.Hello.Hello.Hello.Hello.Hello.He...$ fold -w 20 fileHello.Hello.Hello.Hello.Hello.Hello.Hello.Hello.Hello.Hello.Hello.Hello.Hello.Hello.Hello.Hello.Hello.Hello.Hello.Hello.Hello.Hello.Hello.Hello.Hello.Hello.Hello.Hello.Hello.Hello.Hello.Hello.Hello.Hello.Hello.Hello.Hello.Hello.Hello.Hello.Hello.Hello.Hello.Hello.Hello.Hello.Hello.Hello.Hello.Hello.Hello.Hello.Hello.He...

From man fold:

fold - wrap each input line to fit in specified width

-w, --width=WIDTH

use WIDTH columns instead of 80

So in fact fold file is the same as fold -w 80 file


You could use perl one liner,

perl -lpe 'BEGIN{ $/ = \80 }' file

From peldoc perlvar

$/

The input record separator, newline by default. [..] Setting $/ to a reference to an integer, scalar containing an integer, or scalar that's convertible to an integer will attempt to read records instead of lines, with the maximum record size being the referenced integer number of characters


try option -u

-u (--unbuffered)

Buffer both input and output as minimally as practical. (This is particularly useful if the input is coming from the likes of ‘tail -f’, and you wish to see the transformed output as soon as possible.)

sed -u 's/\(.\{5\}\)/\1\'$'\n/g'