Get values in string after a specific keyword

Hello MacScripter-Community,

I can’t get my current script to work properly. Here’s my situation:

I have a text file (.txt) with multiple lines. Let’s imagine the following lines as the content of the txt-file:

Now I need an Applescript to get all values behind the keyword "Quantity: " so my result should be 2, 40 and 856.

My attempt to solve this is calling a shell script that uses grep to get every line with the keyword "Quantity: ".
In the next step I want to iterate through all lines and extract the value behind "Quantity: "

My Applescript looks like this for now:

set searchString to "Quantity: "
set extrakt to do shell script "grep " & searchString & " /Users/johndoe/Desktop/test.txt"

set trim_chars to "/Users/johndoe/Desktop/test.txt:Quantity: "
set trim_indicator to 0
set extrakt to trim_line(extrakt, trim_chars, trim_indicator)

on trim_line(this_text, trim_chars, trim_indicator)
	-- 0 = beginning, 1 = end, 2 = both
	set x to the length of the trim_chars
	-- TRIM BEGINNING
	if the trim_indicator is in {0, 2} then
		repeat while this_text begins with the trim_chars
			try
				set this_text to characters (x + 1) thru -1 of this_text as string
			on error
				return ""
			end try
		end repeat
	end if
	return this_text
end trim_line

display dialog extrakt buttons {"OK"}

My output in the dialog before trimming is the following:

After trimming I get this:

I totally understand why it is doing that, but I don’t know how to extract every value after the keyword. I guess there is also a much better way to do this kind of stuff, but I don’t know how.

My goal is to add all values after "Quantity: " together, so in this example my final output of the AppleScript should be 898 which is stored in a variable.

Can anyone help me with this please? I’m sorry for some grammar mistakes that may be in that post, english is not my native language =)

Best reagrds,

hallleron

You may try to use :

(*
set theText to "Quantity: 2
Lorem ipsum...
Quantity: 40 Some text here
Lorem ipsum...
Quantity: 856
Lorem ipsum..."
*)

set sourceFile to choose file of type {"txt"}

set theText to read sourceFile

set aList to rest of my decoupe(theText, "Quantity: ")

set theValues to {}
repeat with aText in aList
	set avalue to item 1 of my decoupe(aText, {space, linefeed, return})
	set end of theValues to avalue as number
end repeat
theValues

#=====

on decoupe(t, d)
	local oTIDs, l
	set {oTIDs, AppleScript's text item delimiters} to {AppleScript's text item delimiters, d}
	set l to text items of t
	set AppleScript's text item delimiters to oTIDs
	return l
end decoupe

#=====

Yvan KOENIG running El Capitan 10.11.1 in French (VALLAURIS, France) mercredi 25 novembre 2015 20:59:48

Well, what shall I say… It works!

Thank you very much! :slight_smile:

Problem solved

Thanks for the feedback.

Yvan KOENIG (VALLAURIS, France) jeudi 26 novembre 2015 19:46:38