From: Konrad Meyer Date: 2007-08-10T18:20:04+09:00 Subject: Re: newbie question: how to seek in a file --nextPart2829944.Qna3f4A2ic Content-Type: text/plain; charset="utf-8" Content-Transfer-Encoding: quoted-printable Content-Disposition: inline On Friday 10 August 2007 02:09:56 am Konrad Meyer wrote: > On Friday 10 August 2007 01:43:13 am Ak 756 wrote: > > I want to find a string in a text file, then read some bytes data after > > the position of this string. Would anybody kindly help to tell me how to > > do? >=20 > If this is what you really want, you can do something like: >=20 > READ_BYTES =3D 16 > my_file_contents =3D File.open('foo'){|f| f.read } > my_file_contents =3D~ /find this string(.{#{READ_BYTES}})/ > my_data =3D $1 Better yet: READ_BYTES =3D 16 content =3D File.open('foo'){|f| f.read } my_data =3D content[content.index("find this string"), READ_BYTES] # I tried to combine Lutz's and my earlier ideas Though this of course assumes the string is found. > Of course, this is no good for large files. Generally if you're trying to > extract data from a large text file though, you should already know where= it > is (constant width records) or you have to parse through everything before > the record you want to get at the one you do (csv, xml?). >=20 > If this is for a configuration file or some sort of semi-static storage, = I'd > recommend using YAML or Marshal instead of making your own parser. =2D-=20 Konrad Meyer http://konrad.sobertillnoon.com/ --nextPart2829944.Qna3f4A2ic Content-Type: application/pgp-signature; name=signature.asc Content-Description: This is a digitally signed message part. -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.4.7 (GNU/Linux) iD8DBQBGvC3ECHB0oCiR2cwRAq2sAKCcYRt5AkFq3LYFmaPntuyYR9fZjQCfR/Pi XhiZmxtfXJkLqseesVpY26I= =AzUZ -----END PGP SIGNATURE----- --nextPart2829944.Qna3f4A2ic--