text processing ( sed/awk)

hi..
I have a file having record on in 1 line....

I want every 400 characters in a new line...

means in 1st line 1-400
in 2nd line - 401-800 etc

pl help.

sed -e "s/.\{400\}/&\n/g" file.txt

hi vino...
its not working..
its showing me the same output...
i tested in a small file having abcdefghijklmopqrstuvwxyz in a line....

so after -e "s/.\{4\}/&\n/g" file.txt

the output should be
abcd
efgh
ijkl
lmno
...
...

but its unchaged..

pl help

total_chars=`wc -c filename | cut -c 1-8 `
block_size=400
cut_from=1
cut_to=400
total_chars=`expr $total_chars + 0`
#The above step is to get total_chars treated as number for below comparison
while [ $cut_from -le $total_chars ]
do
cut -c `echo $cut_from`-`echo $cut_to` filename >> outfile
cut_from=`expr $cut_from + $block_size`
cut_to=`expr $cut_to + $block_size`
done

A solution with awk:

awk 'BEGIN{nr=1}{while(substr($0,nr,400)){print substr($0,nr,400);nr+=400}}' file

Regards

Thanks Franklin52,:slight_smile:

hi anchal_khare,

u can also check the below code

awk '{n=1;while( n<=length($0)) { t = substr($0,n,4); print t"\n"; n= n+4} }' Filename

Input:
abcdefghijklmnopqrstuvwxyz

output
abcd

efgh

ijkl

mnop

qrst

uvwx

yz

very thanks for evy1 soln....
'll use any of thm...

1 request .. can any1 chk the vino's soln.. why its nor working...
logic seems to be current,,, but i cunt find out the error...

thanks again..

anchal.

sed will output the changes to stdout. It will not make the changes permanent to the file unless you tell it to.

If you sed supports the -i flag use

sed -i -e "s/.\{400\}/&\n/g" file.txt

If not

sed -e "s/.\{400\}/&\n/g" file.txt >out.txt

out.txt will contain the desired output.

hi vino...
yes i knw what u told....

the output ( stdout ) is unchanaged...
have u tested ur command.. ?

[/tmp]$ cat t
abcdefghijklmopqrstuvwxyz
[/tmp]$ sed -e "s/.\{4\}/&\n/g" t
abcd
efgh
ijkl
mopq
rstu
vwxy
z
[/tmp]$ 

Try

sed -e "s/.\{4\}/&\\n/g" t

wondered... !!!
the same goes here with unchanged o/p.

-bash-2.05b$ cat 400.txt
abcdefghijklmopqrstuvwxyz

-bash-2.05b$ sed -e "s/.\{4\}/&\n/g" 400.txt
abcdnefghnijklnmopqnrstunvwxynz

also tried double escaped.. :slight_smile:

what cud be the reasonn..??

now i tried on linux..

it working...
what cud be the prob with HP-UX?

deleted.
reason : duplicate post.

version inconsistincies with handling newlines in RH side of substitution...

It does work for anything other than \n in Solaris sed also:

#  sed -e "s/.\{4\}/&%/g" infile
abcd%efgh%ijkl%mopq%rstu%vwxy%z

So...a workaround:

#  sed -e "s/.\{4\}/&%/g" infile | tr "%" "\n"
abcd
efgh
ijkl
mopq
rstu
vwxy
z