ScriptSpot

Forum topic · General Scripting

reverse Filter String until FileDoesExist

By JokerMartini · 2011-07-28

Description

I want to create loop that runs through a string until it finds the first DoesFileExist == true and then execute the script.

for example:

varString = C:\users\mike\donuts\bunnies\v01

(run backwards through string checking until true) varString
C:\users\mike\donuts\bunnies\v01 = FALSE
C:\users\mike\donuts\bunnies = FALSE
C:\users\mike\donuts = TRUE


stringn = "C:\Users\Joker\Desktop\cool\maybe\v01"

for i=1 to stringn.count do
(
tempStream = (substring stringn 1 (stringn.count as integer - i))
isValidDir = doesFileExist tempStream

print tempStream
print isValidDir
)

Comments (5)

Thanks

JokerMartini · 2011-08-02

Thank you Anubis for helping out.

my logical mistake :)

Anubis · 2011-07-29

it happens often when i write a directly to the site without testing :) so, thanks for asking. Now the While loop not break due to the boolean test (pathParts.count > 0) that return true to the end. So, here is fixed function:

fn searchPath str = (
	local result = ""
	local isValidDir = false
	local pathParts = filterString str "\\"
	for n = pathParts.count to 1 by -1 while not isValidDir do
	(
		local tmpStr = ""
		for i = 1 to n do tmpStr += pathParts[i] + "\\"
		if (isValidDir = doesFileExist tmpStr) do result = tmpStr
	)
	result
)

Anubis

JokerMartini · 2011-07-29

When I run the code below it returns = "C:\"
When in reality the folders go as deep as = "C:\Users\Joker\Desktop\cool\"

So it should be returning that = "C:\Users\Joker\Desktop\cool\

Why is that?


myPath= "C:\Users\Joker\Desktop\cool\maybe\v01"
fn searchPath str = (
local result = ""
local isValidDir = false
local pathParts = filterString str "\\"
while pathParts.count > 0 or not isValidDir do (
local tmpStr = ""
for p in pathParts do tmpStr += p + "\\"
if (isValidDir = doesFileExist tmpStr) do result = tmpStr
deleteItem pathParts pathParts.count
)
result
)

searchPath myPath

Anubis · 2011-07-28

I think you can optimize a bit the function if you kick out the 'return' call. Something like ... (I write it on-the-fly, ie not tested):

fn searchPath str = (
	local result = ""
	local isValidDir = false
	local pathParts = filterString str "\\"
	while pathParts.count > 0 or not isValidDir do (
		local tmpStr = ""
		for p in pathParts do tmpStr += p + "\\"
		if (isValidDir = doesFileExist tmpStr) do result = tmpStr
		deleteItem pathParts pathParts.count
	)
	result
)

solution if anyone needs it!

JokerMartini · 2011-07-28

stringn = "C:\Users\Joker\Desktop\cool\maybe\v01"

fn searchString = (
pathParts = filterString stringn "\\"
while pathParts.count > 0 do
(
testString = ""
for p in pathParts do testString += p + "\\"
print testString
isValidDir = doesFileExist testString
if isValidDir == true then
return tempStream
deleteItem pathParts pathParts.count
)
)
dirThatExists = searchString()