Ryan
Ryan

Reputation: 15270

How can I add a new line to a large file every n characters in terminal (one liner sed)?

What am I missing here?

file.txt:

ABCDEFGHIJKLMNOPQRSTUVWXYZ

in Terminal:

> sed "s/.\{3\}/&\n/g" < file.txt > new-file.txt

result: new-file.txt

ABCnDEFnGHInJKLnMNOnPQRnSTUnVWXnYZ

Expected Result:

ABC
DEF
...
VWX
YZ

Upvotes: 4

Views: 4786

Answers (6)

Erik
Erik

Reputation: 7352

An option, although maybe not quite correct depending on your input file is the gnu coreutil fold. This will wrap lines so that no line is more than w characters long, e.g.:

$ <<< 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' fold -w3
ABC
DEF
GHI
JKL
MNO
PQR
STU
VWX
YZ

Upvotes: 2

James Youngman
James Youngman

Reputation: 3733

$ echo abcdefghi | dd cbs=3 conv=unblock 2>/dev/null 
abc
def
ghi

Upvotes: 4

glenn jackman
glenn jackman

Reputation: 247042

Just with bash:

while read -n 3 chars; do printf "%s\n" "$chars"; done < file.txt > new-file.txt

Upvotes: 2

Ryan
Ryan

Reputation: 15270

The following ended up working for me:

perl -0777 -pe 's/(.{3})/\1\n/sg' < file.txt > new-file.txt

Still not sure why the original didn't work.

Thanks for your help.

Upvotes: 0

kev
kev

Reputation: 161894

Use sed:

$ sed 's/.../&\n/g' file.txt

Or use grep:

$ grep -oE '.{1,3}' file.txt

result:

ABC
DEF
GHI
JKL
MNO
PQR
STU
VWX
YZ

Upvotes: 6

jcollado
jcollado

Reputation: 40414

One way to do it is to explicitly hit the Enter key while typing the sed command:

$ sed 's/.\{3\}/&\ 
/g' < file.txt > new-file.txt
$ cat new-file.txt
ABC
DEF
GHI
JKL
MNO
PQR
STU
VWX
YZ

Upvotes: 1

Related Questions