The awk
approach you gave as an example is fundamentally different to what you ask. With awk
you do some text processing ON THE FLY (at the same time each line is read), it is not equivalent to 1/read ALL the text first, then 2/ do the filtering, processing on the whole text saved in memory. These involve completely different strategies.
You can actually do something similar to awk
in Mathematica using Low level functions:
To read every other line on the fly, you can do for example:
(* Here is the way to create the dummy file, "file.txt", example I use in the test:
Table["Blabla # "<>ToString[i]<>"\n", {i, 10}]//StringJoin//Export["file.txt", #] &
*)
stream = OpenRead["file.txt"];
NestWhileList[
(Skip[stream, Record]; Read[stream, Record])&,
(Read[stream, Record]),
# =!= EndOfFile &,
1, Infinity, -1]
Close[stream]
{"Blabla # 1", "Blabla # 3", "Blabla # 5", "Blabla # 7", "Blabla # 9"}
In case you don't know, it is also possible to run directly from Mathematica the awk's code (or some other external command) and retrieve the result, for example here:
ReadList["!awk 'NR % 2!=0' file.txt", String]
{"Blabla # 1", "Blabla # 3", "Blabla # 5", "Blabla # 7", "Blabla # 9"}
awk 'NR % 2!=0' file.txt
$\endgroup$