Hayate Yamato
Hayate Yamato

Reputation: 43

Extracting values from text file using autohotkey

I have a small text file that I would like to extract some values using autohotkey.

Example of text file's content:

  Date: 2014-12-02 12:06:47
 Study: G585.010.411
 Image: 6.24
 Tlbar: 2.60
 Notes: 0.74

My current code:

FileReadLine, datetime, C:\File.txt, 1
datedsp := SubStr(datetime, 7)
Sleep 500
FileReadLine, study, C:\File.txt, 2
studydsp := SubStr(study, 7)
Sleep 500
FileReadLine, image, C:\File.txt, 3
imgdsp := SubStr(image, 7)
Sleep 500
FileReadLine, notes, C:\File.txt, 5
notesdsp := SubStr(notes, 7)
Sleep 500

MsgBox %datedsp%
MsgBox %studydsp%
MsgBox %imgdsp%
MsgBox %notesdsp%

All I want to do is to grab the value of each of those lines and assign it to variables. For example, studydsp value would be G58500411, imagedsp value would be 6.24, datedsp value would be 2014-12-02 12:06:47.

Is there anyway to achieve this in a better way?

Possible issues with this code:

  1. I am unable to get the string from the date line perhaps due to a space at the beginning(?)
  2. I can't get the SubStr value of either date (refer to 1st issue) or study (perhaps because of special characters?)

Upvotes: 1

Views: 2115

Answers (2)

MCL
MCL

Reputation: 4065

Basically the same as @blackholyman's answer, but using an object based approach by building a value map:

fileCont = 
(
Date: 2014-12-02 12:06:47
Study: G585.010.411
Image: 6.24
Tlbar: 2.60
Notes: 0.74
)

valueMap := {}

; Alternatively, use: Loop, Read, C:\file.txt
Loop, Parse, fileCont, `r`n
{
    RegExMatch(A_LoopField, "(.*?):(.*)", parts)
    ; Optionally make keys always lower case:
    ; StringLower, parts1, parts1
    valueMap[Trim(parts1)] := Trim(parts2)

}

msgbox %   "Date = "    valueMap["Date"]
         . "`nImage = " valueMap["Image"]

; We can also iterate over the map
out := ""
for key, val in valueMap
{
    out .= key "`t= " val "`n"
}
msgbox % out

Upvotes: 2

blackholyman
blackholyman

Reputation: 1450

You can use FileRead and RegExMatch

var:="
(
 Date: 2014-12-02 12:06:47
Study: G585.010.411
Image: 6.24
Tlbar: 2.60
Notes: 0.74
)"

;~ FileRead, var, C:\file.txt
pos:=1
while pos := RegExMatch(var, "\s?(.*?):(.*?)(\v|\z)", m, pos+StrLen(m))
    %m1% := m2

msgbox % "Date holds " date
    . "`nStudy holds " Study
    . "`nImage holds " Image
    . "`nTlbar holds " Tlbar
    . "`nNotes holds " Notes

Just remove the var part and uncomment the fileread line, at least thats one way to do it to :)

hope it helps

Upvotes: 3

Related Questions