How to return the line that contains specific information from a file?

I have a read file (lets say eventually its name S and has the below data). How to return the locations (line and position in the line) that contains Hi world?

#filehandle = open("$file");
#S = readlines(filehandle);
#close(S); 
S = "1.59000E+01 1.46239E-01 5.98773E+02 5.78302E-05
     here Hi world
     1.59000E+01 4.77688E-02 3.84714E+02 5.31999E-05
     0
     follow Hi world
     fdfd"
#for example here I would expect something like
(2, 6) # Hi world is located in the second line starting from the 6 character
(5, 8) # Hi world is located in the fifth line starting from the 6 character 

You can use eachline to loop over the lines, and then match to use Regex and find occurrences of Hi world.

julia> function f(file)
           r = Tuple{Int,Int}[]
           for (i, line) in enumerate(eachline(file))
               if (m = match(r"Hi world", line); m !== nothing)
                   push!(r, (i, m.offset))
               end
           end
           return r
       end;

shell> cat file.txt
1.59000E+01 1.46239E-01 5.98773E+02 5.78302E-05
here Hi world
1.59000E+01 4.77688E-02 3.84714E+02 5.31999E-05
0
follow Hi world
fdfd

julia> f("file.txt")
2-element Vector{Tuple{Int64, Int64}}:
 (2, 6)
 (5, 8)
2 Likes

@fredrikekre Thank you very much.
I have put the below code in julia file (.jl) and in the same folder I put the file.tex which contains string data. But I am having the below error.

function f(file)
  r = Tuple{Int,Int}[]
  for (i, line) in enumerate(eachline(file))
      if (m = match(r"Hi world", line); m !== nothing)
          push!(r, (i, m.offset))
      end
  end
  return r
end
file = "C:/Users/.../file.txt"; # I put here the full directory
f("file")

ERROR: LoadError: SystemError: opening file "file": No such file or directory
Stacktrace:

Did you try: file = raw"copy and paste full path here"

1 Like

Yes, and still the same error

you want
f(file)

since file is a variable containing the appropriate string. You are asking it to open the file named “file”

3 Likes

Thank you, yes now it works.

Fyi, you could use Regex() to extend @fredrikekre’s function and create the regex string programmatically.

function findsentence(file, sentence)
    r = Tuple{Int,Int}[]
    for (i, line) in enumerate(eachline(file))
        if (m = match(Regex("$sentence"), line); m !== nothing)
            push!(r, (i, m.offset))
        end
    end
    return r
end

file = raw"C:\...\Find_Hi_world.txt"
sentence = "Hi world"
findsentence(file, sentence)
# result:
 (2, 6)
 (5, 8)
1 Like