Parsing a text file with columns? Topic is solved

Get help with using AutoHotkey (v1.1 and older) and its commands and hotkeys
chinagreenelvis
Posts: 133
Joined: 19 Oct 2015, 16:21

Parsing a text file with columns?

Post by chinagreenelvis » 22 Jan 2022, 06:15

I have a text file that needs to be read, and each line has two items on it that need to be put into separate variables for each loop:

Code: Select all

somefile.ext     "title of the file with spaces A"
somefile2.ext    "title of the file with spaces B"
I can do this in a batch file with the following:

Code: Select all

FOR /F "usebackq tokens=1*" %%a IN ("%listfile%") DO (
	set "filename=%%~a"
	set "filetitle=%%~b"
)
However, I'm trying to convert that script to an AHK file instead. Is there an easy way to do this?

chinagreenelvis
Posts: 133
Joined: 19 Oct 2015, 16:21

Re: Parsing a text file with columns?

Post by chinagreenelvis » 22 Jan 2022, 06:30

I've worked out something that seems to be on the right track:

Code: Select all

Loop, Read, list.txt
{
	MsgBox, %A_LoopReadLine%
	Count := 0
	Loop, Parse, A_LoopReadLine, "
	{
		Count++
		MsgBox, %A_LoopField%
		If (Count = 2)
		{
			Break
		}
	}
}
But I'm still wondering if there is a simpler way.

User avatar
boiler
Posts: 16927
Joined: 21 Dec 2014, 02:44

Re: Parsing a text file with columns?  Topic is solved

Post by boiler » 22 Jan 2022, 06:54

FileRead is better than a file reading loop, especially if your file will contain a lot of lines. You can use a parsing loop on that text that was read in and use RegExMatch to pull out the two pieces of data from each line and add them to an array.

Code: Select all

; place the data in an array:
Data := []
FileRead, Text, list.txt
loop, Parse, Text, `n, `r
{
	RegExMatch(A_LoopField, "([^""]*)(.*)", Match)
	Data.Push({filename: Trim(Match1), filetitle: Match2})
}

; display the array contents:
Output := ""
for Each, Item in Data
	Output .= "File name: " Item.filename "`nFile title: " Item.filetitle "`n`n"
MsgBox, % Output

The data is in an array with one element for each line, where each line element contains a two-element array, one with the key "filename" and the other "filetitle". So the first line's data is in Data.1.filename and Data.1.filetitle, and the second line is in Data.2.filename and Data.2.filetitle.

Do you want the title to include the quotes or have them removed before they are saved to the array? Currently, it includes the quotes. To not include them, just change the RegExMatch line to this:

Code: Select all

	RegExMatch(A_LoopField, "([^""]*)""(.*)""", Match)

chinagreenelvis
Posts: 133
Joined: 19 Oct 2015, 16:21

Re: Parsing a text file with columns?

Post by chinagreenelvis » 22 Jan 2022, 21:32

This is much more efficient, thanks very much.

Post Reply

Return to “Ask for Help (v1)”