Update Properties of Files from Search Results in Bulk

Here is a fully working example:

```dataviewjs
const tp = app.plugins.plugins['templater-obsidian'].templater.current_functions_object

const result = await dv.query(`
  LIST
  WHERE file.folder = this.file.folder
    AND file != this.file
`)

if ( result.successful ) {
  const values = result.value.values
  for (const f of values) {
    const tFile = await tp.file.find_tfile(f.path)
    await app.fileManager.processFrontMatter(tFile, (fm) => {
      console.log(fm, Object.keys(fm).length)
      if (Object.keys(fm).length == 0) {
        fm['initiallyEmpty'] = true
      } else { 
        if (fm['one']) {
           fm['one'] = fm['one'].toUpperCase()
        }
        delete fm['toBeDeleted']
      }
    })
  } 
} else
  dv.paragraph("~~~~\n" + result.error + "\n~~~~")
```

Here the query simply lists the file in my current folder, excluding the file of the query. Then it proceeds to uppercase the one property, delete the toBeDeleted property, and if no properties add the initiallyEmpty property. I’m using a little trickery to include the find_tfile() from the Templater plugin, so this query relies on both Dataview and Templater. Not sure if (or how) I can locate the tFile using other means.

To showcase my test setup, I ran this query:

```dataview
TABLE file.frontmatter
WHERE file.folder = this.file.folder
  AND file != this.file
```

The before run showed this:
image

And the after run has this output:
image

And as expected the wanted changes has occurred.

Some caveats using stuff like this:

  • Be sure not to cause any recursive editing of properties which can occur if your current file holds a query displaying values/files you’re going to change. The update of the files trigger a refresh of the queries in the current file, aka also running your update frontmatter script again…
  • You might experience issues if some of your files are open in other tabs, but it should work
  • Please do multiple dry-runs checking what you want to change, before actually doing the changes. Both to verify that your query actually hits the correct files, and that the changes you intend to do are the correct changes to do. A tool like this can explode/change your vault drastically
  • Please do make a backup of your vault before doing a larger run!!!
5 Likes