TransWikia.com

Reference line number of string from text file

TeX - LaTeX Asked by Lucas Paul on April 25, 2021

I want to reference a line from a non-TeX text file that contains a fixed string. I just want to be able to get its line number. I’ll need to do this several times for the same file, so it’d be nice if any solution didn’t have to read the file each time it’s used.

I found another SE question that had to do with listings that almost sorta kinda does what I want. It uses an escape character and embeds links into the source file. I could almost use this, but there are two things I don’t like about it. 1. It would require me to edit the text file and add an escape character and some TeX code. I’d really rather not do this. 2. It seems to include the listing in the final result (pdf, whatever), which I do not need or want.

One Answer

If the file is composed purely of textual material, then this approach might work. I use readarray to import the file into a def with line separators added. Then I use a nested listofitems parsing to find the line containing the defined matchstring. The result is a macro lineindex containing the row number of the matched string in the file.

The types of characters that will break the file read, since it is being read in LaTeX are:

  1. #

  2. % will act as a comment and blot the remainder of the input line.

  3. unbalanced { or }

  4. ... that forms an undefined macro name.

The MWE:

documentclass{article}
usepackage{readarray,listofitems,pgffor}
begin{filecontents*}[overwrite]{mydata.txt}
fgfdg dg f
ytryn  fghgfh
565hhyj fhjfhj
tytr6um jyj
end{filecontents*}
begin{document}
defmatchstring{j fhjf}% THE STRING OF INTEREST
readarraysepchar{}
expandaftersetsepcharexpandafter{expandafterexpandafter/matchstring}
readdef{mydata.txt}mydatafile
readlistmydata{mydatafile}
foreachitemzinmydata[]{ifnumlistlenmydata[zcnt]>1relax
  xdeflineindex{zcnt}fi}

The line index containing the matchstring is lineindex.
end{document}

enter image description here

Answered by Steven B. Segletes on April 25, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP