I need to extract text from within text using the following example:
Number ‘178354’ Name = ‘blue’
Number ‘840923’ Name = ‘red’
Number ‘396834’ Name = ‘yellow’
I need to extract the number associated with the line that contains yellow. The number is dynamic but the names are static – there will always be only one line that contains the name yellow but the number will be different. Thanks.
set test to "Number '178354' Name = 'blue'
Number '840923' Name = 'red'
Number '396834' Name = 'yellow'"
do shell script "echo " & quoted form of test & " | grep 'yellow' | grep -o '[[:digit:]]\\+'"
set astid to AppleScript's text item delimiters
set AppleScript's text item delimiters to "'"
set x to "Number '396834' Name = 'yellow'"
if text item -2 of x is "yellow" then
set num to second text item of x
end if
display dialog num
set AppleScript's text item delimiters to astid
x would be the variable that your text string would be set to in your script.
PreTech
P.S. the display dialog was just to see the result was correct.
If you have more than one line, you might do something like this:
set ASTID to AppleScript's text item delimiters
set AppleScript's text item delimiters to {"'"}
set theNumber to missing value -- in case we don't find the "yellow" line
get paragraphs of "Number '178354' Name = 'blue'
Number '840923' Name = 'red'
Number '396834' Name = 'yellow'"
repeat with thisLine in result
if text item -2 of thisLine is "yellow" then
set theNumber to second text item of thisLine
exit repeat
end if
end repeat
set AppleScript's text item delimiters to ASTID
return theNumber
Alternatively, if the number is always six digits, you might be able to do this instead:
set test to "Number '178354' Name = 'blue'
Number '840923' Name = 'red'
Number '396834' Name = 'yellow'"
get offset of "yellow" in test
return text (result - 16) thru (result - 11) of test
You could open Terminal and type “man grep”. You could also look for grep tutorials.
on |number| for c from t
word 2 of paragraph -1 of t's text 1 thru (offset of c in t)
end |number|
set sourceText to "Number '178354' Name = 'blue'
Number '840923' Name = 'red'
Number '396834' Name = 'yellow'"
|number| for "blue" from sourceText
--> "178354"
|number| for "red" from sourceText
--> "840923"
|number| for "yellow" from sourceText
--> "396834"