Is there a way to make ReadList ignore certain "comment lines" (say, all lines that start with #, or in general all lines that match a string pattern)? This would be very useful for many types of files.

  • $\begingroup$ How are you using ReadList, reading in the whole file at once via ReadList["file"] or reading in a certain number of lines each time via ReadList["file",types,n]? $\endgroup$ – Jason B. Jan 25 '16 at 13:14
  • $\begingroup$ @JasonB Up to now I've done ReadList["file"], but maybe ReadList["file",types,n] is more convenient to ignore comments? $\endgroup$ – becko Jan 25 '16 at 13:16
  • $\begingroup$ So if you've read in the whole file using ReadList["file"], then can't you simply remove the elements that match the pattern? $\endgroup$ – Jason B. Jan 25 '16 at 13:18
  • $\begingroup$ I don't think ReadList supports this. Two ideas: 1. read the whole file as a string, filter the comments, convert the string to a stream, read from there 2. use sed to strip the comments, pipe the output to Mathematica (i.e. ReadList["!sed ..."] where you'll need to look up the correct arguments to sed). $\endgroup$ – Szabolcs Jan 25 '16 at 14:04
  • $\begingroup$ possible dup : mathematica.stackexchange.com/q/50718/2079 $\endgroup$ – george2079 Jan 25 '16 at 14:25

george2079's answer works great for ignoring comment lines, but it uses Import to read in the whole file at once. Sometimes you have really large files that you can't Import in one go, you have to read them line by line. Of course, for files where you can use Import, that will be faster because you are applying the test to the one big string instead of to each line one after the other.

So should it ever be needed, here is this slower method,

readTableIgnoreComments[fname_, comment_] := 
  Module[{stream, input, list},
   stream = OpenRead[fname];
   input = ReadLine[stream];
   list = Reap[
      While[input =!= EndOfFile,
        input = StringReplace[input, StartOfLine ~~ "#" ~~ __ -> ""];

        If[input =!= "",
         Sow[ImportString[input, "Table"][[1]]];
        input = ReadLine[stream];
      ][[2, 1]];

Say you have a data file, like this one.

readTableIgnoreComments["AFmW2BKQ.txt", "#"]


As george2079 and Szabolcs pointed out, if you are lucky enough to be running an operating system with sed, then by far the fastest way to do this is to use sed to replace the commented lines,

readListIgnoreComments[fname_, comment_] := Module[{list},
  Run["sed -e '/^" <> comment <> ".*/d' " <> fname <> " > TEMP_" <> 
  list = ReadList["TEMP_" <> fname];
  DeleteFile["TEMP_" <> fname];

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.