Skip to content
⌘ NSIS Forum Archive

How to parse a string from a txt file?

9 posts

sckoobs#

How to parse a string from a txt file?

Hi there, I'm on my second day of scripting with NSIS and have a need to be able to ready in a value from a text file.

The file format is as follows:
ProductName     = Tools
ProductVersion  = 6.0.2.0
FileVersion     = 6, 0, 2, 0 
Does anyone know of a reliable and easy way to get the values from this file? I've looked at the ConfigRead function but I haven't been able to get it work at all.

Also, hope I'm not clouding the issue here but, does FileOpen accept relative paths?

Any help is much appreciated.
Thanks,
Andy
Afrow UK#
ConfigRead

I would refrain from using relative paths in NSIS scripts in case you change the working directory with SetOutPath.

Stu
LoRd_MuldeR#
The easiest method might be using the INI functions:

Given the following file:
[Info]
ProductName = Tools
ProductVersion = 6.0.2.0
FileVersion = 6, 0, 2, 0
You can read the info like this:
Section
ReadINIStr $0 "$INSTDIR\foobar.ini" "Info" "ProductName"
ReadINIStr $1 "$INSTDIR\foobar.ini" "Info" "ProductVersion"
ReadINIStr $2 "$INSTDIR\foobar.ini" "Info" "FileVersion"
SectionEnd
Afrow UK#
He didn't include a section header in his snippet in which case ReadINIStr would not work.

Stu
Afrow UK#
In fact as you have rightly said ConfigRead won't work here either due to the padding. You will have to use FileRead in a loop with some string manipulation in there to find and chop the bit you want.

Stu
Comperio#
This might help. It uses ConfigRead and WordReplace, both of which are in NSIS help. See the attachment for complete example.

${ConfigRead} "$EXEDIR\test.ini" "ProductName" $1
; remove the "=" sign
${WordReplace} "$1" "=" "" "+" $1
; remove extra tab characters:
${WordReplace} "$1" "$\t" "" "{}" $1
; remove extra white space:
${WordReplace} "$1" " " "" "{}" $1
Afrow UK#
That will work assuming there are no entries like ProductNameXYZ = thus reading the wrong value.

Stu
Senhu#
Parsing using biterscripting when name=value pairs have flexible syntax

Excellent help so far.

Winamp is great. Occasionally I tend to use biterscripting (.com for free download) for simplified parsing.

The following code in biterscripting will get you the values from the file in the flexible syntax you specified.


# START CODE
var str input, line ; cat <file> $input

while ($input <> "")
do
lex -e "1" $input > $line
wex "[3" $line
done
# END CODE

You may want to put this code in a file to create a script, and pass the input file name ($file) as input argument to that script.

The lex command (line extractor), extracts each line.
The wex command (word extractor), extracts [3, that is everything after (and including) the third word on that line. The wex command takes care of variable sytaxes such as name=value, name = value, name \t=value, etc. The system variable $wsep (word separator) specifies what are considered word separators.

Hope this helps.

Sen