Hi All,
My file is a string of around 50K character.
I'm trying to insert new line after every 320 character in my file.
I know the command to insert newline, but problem is I'm not able to search 320th position.
Please advice.
Hi All,
My file is a string of around 50K character.
I'm trying to insert new line after every 320 character in my file.
I know the command to insert newline, but problem is I'm not able to search 320th position.
Please advice.
Try:
sed -e 's_\(.\{320\}\)_\1\n_g' infile
In place replacement:
perl -pi -e 's/(.{320})/\1\n/g' infile
Hi Klash..
Above code is giving me error as "sed: Function s_\(.\{320\}\)_\1\n_g cannot be parsed."
Use fold
instead:
fold -c320 infile > outfile
@Amit786 there must be something wrong , the sed/perl command works fine.
@Yoda , good one i didn't know that utility, Thanks!
There is a limit (RE_DUP_MAX ) to the repetition. In some sed's this seems to be rather low (255 or so). BSD sed does not cut it, GNU sed does..
$ sed 's/.\{320\}/&\
/g' infile
sed: 1: "s/.\{320\}/&\
/g": RE error: invalid repetition count(s)
An example using builtins only, OSX 10.7.5, default shell...
Just a 256 byte ascii file with a newline every 16 bytes...
#!/bin/sh
# Generate a random 256 byte ASCII string and prepare.
> /tmp/ascii
> /tmp/newascii
echo ""
echo "Generating a 256 byte ASCII test string..."
for n in {0..255}
do
printf \\$(printf '%03o' "$[ ( $RANDOM % ( 95 ) + 32 ) ]") >> /tmp/ascii
done
echo "Done..."
echo ""
read -d '' -r text < /tmp/ascii
echo "$text"
echo ""
echo "Now longhand using builtins..."
echo ""
# Set up and preparation done...
# Create newlines every 16 characters...
# Start of conversion proper...
newtext=""
for n in $( seq 0 16 255 )
do
echo "$newtext${text:$n:16}" >> /tmp/newascii
done
# End of conversion proper...
# Proof test...
cat < /tmp/newascii
echo ""
Results:-
Last login: Tue Feb 18 18:52:41 on ttys000
AMIGA:barrywalker~> chmod 755 nl_16.sh
AMIGA:barrywalker~> ./nl_16.sh
Generating a 256 byte ASCII test string...
Done...
+Cax7Om%D[y2Pg'>\s3Jh!?Vu-Kc"@Wv.Ld#:Yp/Fe|;Sq)H_}6Tk*B`w7Nl%CZy1Om&D[z2Ph'>]t3Ji!?Wu-Lc"9Xo.Fd{;Rp)Ge|<Sq*H_~6Tl+B`x7Nm%C[y1Pg&=\s2Jh ?Vt4Ki!@Wu.Lc#:Xo/Fd|;Rq)G_}5Sk*A`w6Nl+Cax7Om%D[y2Pg'>\s3Jh!?Vu-Kc"9Wo.Ed{:Yp/Fe|;Sq)H_}6Tk*B`w7Nl%CZy1Of&=[s2Ph'>]t3Ji!?
Now longhand using builtins...
+Cax7Om%D[y2Pg'>
\s3Jh!?Vu-Kc"@Wv
.Ld#:Yp/Fe|;Sq)H
_}6Tk*B`w7Nl%CZy
1Om&D[z2Ph'>]t3J
i!?Wu-Lc"9Xo.Fd{
;Rp)Ge|<Sq*H_~6T
l+B`x7Nm%C[y1Pg&
=\s2Jh ?Vt4Ki!@W
u.Lc#:Xo/Fd|;Rq)
G_}5Sk*A`w6Nl+Ca
x7Om%D[y2Pg'>\s3
Jh!?Vu-Kc"9Wo.Ed
{:Yp/Fe|;Sq)H_}6
Tk*B`w7Nl%CZy1Of
&=[s2Ph'>]t3Ji!?
AMIGA:barrywalker~> _