Looking up data from a file, and storing them as variables - autohotkey

I'm new to autohotkey and I can't figure out how to solve this. Any help is appreciated.
I have list.txt which includes ids and names like this:
list.txt:
123124 - whatever
834019 - sometext
3980 - afjalkfj
I need a function that can do the following
lookup(id, name){
** The function here should lookup for the id inserted
then save ONLY the data related to it in variable x (not the full line)
}
Example
lookup(834019, x)
%x% = sometext
Please help me to do this. Thanks!

What you need in this case are
FileRead to read the file's contents into a variable.
A parsing loop to parse the text of each line.
The StrSplit() function to split the text of each line into an
array of Substrings using the specified Delimiters.
The second parameter (name) is redundant in this case. You can omit it:
x := lookup(834019)
MsgBox, % x
MsgBox, % lookup(3980)
lookup(id) {
FileRead, Contents, list.txt ; read the file's contents into the variable "Contents"
if not ErrorLevel ; Successfully loaded.
{
Loop, parse, Contents, `n, `r ; parse the text of each line
{
word_array1 := StrSplit(A_LoopField," - ").1 ; store the first substring into the variable "word_array1"
word_array1 := Trim(word_array1, " `t") ; trim spaces and tabs in this variable
If (word_array1 = id)
{
name := StrSplit(A_LoopField," - ").2
name := Trim(name, " `t")
return name
}
}
Contents := "" ; Free the memory.
}
else
MsgBox, A problem has been encountered while loading the File Contents
}

Related

How to check what the first word in clipboard is?

Lets say my Cliboard variable is currently in this state:
Clipboard:= "-Classes Essay on Hobbes
I want to perform If conditions depending on the first block/word in the clipboard, in this case -Classes . Essentially doing something like below using FileAppend:
if "-diary"{
;Create file in /Diary/Entry 27.MD
}
Else if "-Classes"{
;Create file in /Classes/Essay on Hobbes.MD
}
I was able to find this page in the docs If Var in/contains MatchList - Syntax & Usage | AutoHotkey but its not positional, which means if the block -Classes is also present as part of the file name for some reason, my logic breaks.
I have taken the liberty to crosspost this question on other forums as well.
Any help would be greatly appreciated!
Or.. you can just:
Clipboard:= "-Classes Essay on Hobbes"
Gosub % subroutine := SubStr( Clipboard, 1, InStr( Clipboard, " " )-1 )
Clipboard:= "-diary diary example"
Gosub % subroutine := SubStr( Clipboard, 1, InStr( Clipboard, " " )-1 )
Return
-diary:
MsgBox % "Diary:`n" StrReplace( clipboard, subroutine " " )
;Create file in /Diary/Entry 27.MD
Return
-Classes:
MsgBox % "Classes:`n" StrReplace( clipboard, subroutine " " )
;Create file in /Classes/Essay on Hobbes.MD
Return
You might try StrSplit()
; Array := StrSplit(String , Delimiters, OmitChars, MaxParts)
clip_array := StrSplit(Clipboard, A_Space, , 1)
if clip_array[1] = "-diary"{
;Create file in /Diary/Entry 27.MD
}
Else if clip_array[1] = "-Classes"{
;Create file in /Classes/Essay on Hobbes.MD
}
Else {
MsgBox % "No match for " clip_array[1]
}
Described here https://www.autohotkey.com/docs/commands/StrSplit.htm and note the param for MaxParts which addresses how many "tokens" to look in to (keeping the rest in the last) if the clipboard is sufficiently large to matter (in which case I'm not sure any of the other answers address any better).
If the amount of text on the clipboard is enormous, that could cause lagging with the script loading all of that text into the script memory, just to check the first value. I'd recommend regexMatch since that can return a position and capture the word as well without parsing everything.
; for reference of regexMatch function
; regexMatch(Haystack, Needle, outputVar, startPos)
Fnd := regexMatch(Clipboard, "U)(\-[\w]+))", capSubStr, inStr(Clipboard, "-"))
if (Fnd==0) {
Msgbox, Didn't find a word on the Clipboard.
Return
}
checkVal := capSubStr1
if (checkVal=="-diary") {
;Create file in /Diary/Entry 27.MD
} Else if (checkVal=="-Classes") {
;Create file in /Classes/Essay on Hobbes.MD
}
Here is the basic reference for using regular expressions with AHK: https://www.autohotkey.com/docs/misc/RegEx-QuickRef.htm
That will give an idea as to what the above expression is actually looking for, if you are not already familiar with regex.

Split String in Array into an array autohotkey

Trying to read a CSV file in Auto Hot Key and line by line split the line by "," to pull out the last two columns of each line. Currently just trying to get the string to split into an array. I can print each line with the line
MsgBox, A_LoopReadLine but cannot split the string inside of the variable.
Have tried StringSplit and StrSplit but I am sure the syntax is incorrect.
MyArray := Object()
Loop, read, %fileop%
{
MyArray.Insert(A_LoopReadLine) ; Append this line to the array.
index := 1
MsgBox, %A_LoopReadLine%
;MyArray.
;MsgBox, % StrSplit(A_LoopReadLine ,",")
}
Loop % MyArray.Length()
MsgBox % StrSplit(MyArray[A_Index],",")
Trying to read a CSV file in Auto Hot Key and line by line split the
line by "," to pull out the last two columns of each line.
MyArray := Object()
Loop, Read, %fileop%
MyArray[A_Index]:=StrSplit(A_LoopReadLine,",")
This will store your csv file in MyArray[row][column] format. E.g to access second item in fifth row: MyArray[5][2]
for k,v in MyArray
v.RemoveAt(1,v.Length()-2)
Above will remove all but last two items from each row.
Documentation:
https://autohotkey.com/docs/commands/For.htm
https://autohotkey.com/docs/objects/Object.htm#RemoveAt_v1121+
https://autohotkey.com/docs/objects/Object.htm#Length
Edit:
And to as to why your code did not work. It kinda did.
The thing is that StrSplit() returns object, array so with below line you were trying to display object in MsgBox, this is not allowed.
MsgBox % StrSplit(MyArray[A_Index],",")
This for example would work:
MsgBox % StrSplit(MyArray[A_Index],",")[1]

Is there a way to assign a multi-line string to a object property?

I know that you can assign a multi-line string to a variable like this:
MyVar =
(
this
is
a
string with multiple
lines
)
But is there a way to assign the above string to an object property? I tried doing it like this but I received an error:
Array := {}
Array["key"] =
(
this
is
a
string with multiple
lines
)
The error says:
The following variable name contains an illegal character
"this
is
a
string"
I just want to be able to open my script in a text editor and copy and paste multiple-line strings directly into the editor as properties of objects.
You have to use the proper assignment operator := with Objects, likewise your text needs be enclosed by Quotes.
Try:
obj := {}
obj["key"] :=
(
"this
is
a
string with multiple
lines"
)
MsgBox % obj["key"]
Or you can do this below:
x =
(
this
is
a
string with multiple
lines
)
obj["key"] := x
MsgBox % obj["key"]
You can also build a multi-line object like so:
obj := {"key":
(
"this
is
a
string with multiple
lines"
)}
MsgBox % obj["key"]
Using a raw multiline string assignment like the following it tends to defeat any indenting you may have cultivated in your script.
str := {"Lines":
(
"first
second
third"
)}
Although that will work. If you're looking to preserve your code indenting then you can create a multiline string by delimiting the lines with `n like this:
str := {"Lines": "first`nSecond`nThird"}

Replace a middle string in .bat file using AutoHotKey without deleting file

I need to edit standalone.bat file using ahk script. I want to increase my heap size using ahk so below is line where i have to change heap in my bat file. Now i have trying to edit this using StringReplace and FileAppend but FileAppend keeps on appending string to the end
from
set "JAVA_OPTS=-Dprogram.name=%PROGNAME% -Xms64M -Xmx1426M %JAVA_OPTS%"
to
set "JAVA_OPTS=-Dprogram.name=%PROGNAME% -Xms64M -Xmx1426M %JAVA_OPTS%"xms000M
I am new to .ahk, i have tried this using some search
Loop, read, C:\standalone.bat
{
Line = %A_LoopReadLine%
replaceto = xms000M
IfInString, Line, Xmx1426M
, Line, replaceto, %Line%, %replaceto%
FileAppend, %replaceto%`n
StringReplace FileAppend
}
Is it possible to replace middle string using ahk. thanks
Fileappend will always append to the end of a file. Why do you want to prevent a temporary deletion of your batch file?
Typically, in ahk, you'd do it like this..
batFile = C:\standalone.bat
output := ""
Loop, read, %batFile%
{
Line = %A_LoopReadLine%
IfInString, Line, Xmx1426M
{
StringReplace, Line, Line, Xmx1426M, xms000M
; note: Regular Expressions can be used like Line := regExReplace(Line, "...", "...")
}
output .= Line . "`n" ; note: this is the same as if to say output = %output%%Line%`n or output := output . line "`n"
}
FileDelete, %batFile%
FileAppend, %output%, %batFile%
This will delete your file for some little milliseconds, just to recreate it with the new content afterwards. I don't really see any difference to editing it without deletion, because in either way, you'll need write access to the file.
Some words about your code sample:
IfInString, Line, Xmx1426M
, Line, replaceto, %Line%, %replaceto%
will be interpreted as
"If the string 'Line' contains 'Xmx1426M , Line, replaceto, %Line%, %replaceto%'"
which does not make any greater sense.
FileAppend, %replaceto%\n is lacking a destination file.
StringReplace FileAppend: these are two commands without any further parameters. You must never put two non-function-commands in the same line!

Remove last n characters of string after the dot with Autohotkey

I am using Autohotkey.
I have a string that looks like this S523.WW.E.SIMA. I want to remove the last few characters of the string after the dot (including the dot itself). So, after the removal, the string will look like S523.WW.E.
This may look like a simple question but I just cannot figure out using the available string functions in Autohotkey. How can this be done using Autohotkey? Thank you very much.
Example 1 (last index of)
string := "S523.WW.E.SIMA"
LastDotPos := InStr(string,".",0,0) ; get position of last occurrence of "."
result := SubStr(string,1,LastDotPos-1) ; get substring from start to last dot
MsgBox %result% ; display result
See InStr
See SubStr
Example 2 (StrSplit)
; Split it into the dot-separated parts,
; then join them again excluding the last part
parts := StrSplit(string, ".")
result := ""
Loop % parts.MaxIndex() - 1
{
if(StrLen(result)) {
result .= "."
}
result .= parts[A_Index]
}
Example 3 (RegExMatch)
; Extract everything up until the last dot
RegExMatch(string, "(.*)\.", result)
msgbox % result1
Example 4 (RegExReplace)
; RegExReplace to remove everything, starting with the last dot
result := RegExReplace(string, "\.[^\.]+$", "")