When I'm located in a given working directory, how can I find a file located any several levels up?
I want to search the file by its name, and I don't know whether the file is located just one directory up, or more levels up. Therefore, I'm looking for a way to go one level up in each time and search for the file. Once it's found, I want to get the absolute full path to the file.
I'm trying to use the {fs} package to this end, but so far don't really know how.
Example
library(fs)
set.seed(2021)
## create a folder in location temp
tmp <- dir_create(file_temp())
tmp
#> /tmp/Rtmpw2JtlE/file31f26c45d04
## create a txt file in `tmp` path
file_create(path(tmp, "my-file.txt"))
## verify the file now exists in `tmp`
dir_ls(tmp)
#> /tmp/Rtmpw2JtlE/file31f26c45d04/my-file.txt
## create a subdirectory within `tmp`, calling it `my_dir`
dir_create(tmp, "my_dir")
## create a subdirectory within `my_dir`, calling it `another_dir`
dir_create(path(tmp, "my_dir_1"), "another_dir")
## create a subdirectory within `another_dir`, calling it `another_dir_2`
dir_create(path(tmp, "my_dir_1"), "another_dir", "another_dir_2")
## now we set the working directory to be at tmp/my_dir_1/another_dir/another_dir_2/
setwd(path(tmp, "my_dir_1", "another_dir", "another_dir_2"))
## verify that the working directory has been set correctly
getwd()
#> [1] "/tmp/Rtmpw2JtlE/file31f26c45d04/my_dir_1/another_dir/another_dir_2"
What I did in the code above was to create the following tree:
tmp
├── my-file.txt
├── my_dir
└── my_dir_1
└── another_dir
└── another_dir_2 ## now this is the working directory
Given that my working directory is another_dir_2, and that the target file is my-file.txt, how could I find the file without knowing that it's 3 levels up? That is, I'd like to first check one level up (i.e., at another_dir), and if my-file.txt is there, return the full path to file. If it's not found at another_dir, go another level up and search there, and so on, until it's found.
Desired Solution
Something like:
find_up("my-file.txt")
## which will return:
[1] "/tmp/Rtmpw2JtlE/file31f26c45d04/my-file.txt"
Any idea how to accomplish this with base R or fs?
Thanks!