简体   繁体   中英

how to remove everything inside directory except a list of files and directories?

I need to delete everything inside dist/ folder except manifest.json and index.html and assets/ . It will run as script inside package.json .

I tried solving it with find

"clean": "find dist. -name manifest.json -type f -delete | find . -type d -empty -delete"

But I couldn't get it to work with multiple arguments.

edit:

So I want to keep:

dist/assets/* everything inside assets. Including subdirectories like dist/assets/map/dog.ts dist/manifest.json
dist/index.html

and delete the rest, for example:

dist/pages/ delete directory, subdirectories and files
dist/examples/ delete directory, subdirectories and files
dist/randomfile.txt delete file
dist/hello.js delete file
dist/* etc. etc.

i think that command is: $ rm -v !("filename")

According to the current version of the question you want to keep

  • dist/assets/ (and everything inside)
  • dist/manifest.json
  • dist/index.html

and remove everything else inside dist .

For testing I used this find command.

find dist -mindepth 1 -maxdepth 1 \
  -type f \( -name manifest.json -o -name index.html -o -print \) -o \
  -type d \( -name assets -o -print \)

If the output lists everything that should get removed in dist you can run the version that actually deletes the data.

find dist -mindepth 1 -maxdepth 1 \
  -type f \( -name manifest.json -o -name index.html -o -print -delete \) -o \
  -type d \( -name assets -o -print -exec rm -rf "{}" \; \)

Explanation:

  • global options -mindepth 1 -maxdepth 1 to limit the search to all files and directories directly below dist .
  • -type f \( actions1 \) -o -type d \( actions2 \) use AND ( -a or nothing) and OR ( -o ) operations to execute actions1 for files and actions2 for directories, use escaped parentheses because AND operation has higher precedence than OR. (If there are any other objects in dist (eg symbolic link, named pipe, ...) you might have to add conditions and some action to catch the other cases.
  • -name manifest.json -o -name index.html -o -print -delete OR operation: if one of the first expressions (matching name) is true, the last one ( -print -delete ) is not executed
  • -name assets -o -print -exec rm -rf "{}" \; similar to above, use rm -rf for recursive removal because -delete will not remove non-empty directories.

Alternative solution:

  • rename dist
  • create a new dist
  • move the files and directory you want to keep to the new dist
  • recursively remove the old renamed directory.
mv dist dist.tmp && mkdir dist &&
  mv dist.tmp/assets dist.tmp/manifest.json dist.tmp/index.html dist && 
  rm -rf dist.tmp

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM