You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用JavaScript读取目录下所有文件夹名并删除非指定格式文件夹?

Got it, let's tackle this problem step by step. You want to scan a directory, filter out folders that don't match the YYYY_M_D (or YYYY_MM_DD) date format (like your example 2018_5_27), and delete those non-compliant ones. Below are practical, cross-platform solutions depending on your toolset:

Bash Script (Unix/Linux/macOS)

If you're working on a Unix-like system, a bash script can get this done quickly. We'll use find to target directories, validate their names with a regex, and delete the ones that don't fit the date pattern.

  1. First, set your target directory (replace /path/to/your/folder with your actual directory path):
    TARGET_DIR="/path/to/your/folder"
    
  2. Use this command to delete non-compliant folders (test first with echo!):
    # Test mode: print which folders will be deleted
    find "$TARGET_DIR" -maxdepth 1 -type d ! -name "." ! -name ".." -regextype posix-extended ! -regex "^$TARGET_DIR/[0-9]{4}_[0-9]{1,2}_[0-9]{1,2}$" -exec echo {} +
    
    # Actual deletion mode (remove echo to delete)
    # find "$TARGET_DIR" -maxdepth 1 -type d ! -name "." ! -name ".." -regextype posix-extended ! -regex "^$TARGET_DIR/[0-9]{4}_[0-9]{1,2}_[0-9]{1,2}$" -exec rm -rf {} +
    

Let's break down what this does:

  • -maxdepth 1 ensures we only check direct subfolders (no nested ones)
  • -type d targets only directories
  • ! -name "." ! -name ".." skips the current and parent directory entries
  • ! -regex ... excludes folders that match our date pattern (so we're left with non-compliant ones)
  • -exec rm -rf {} + deletes those folders and all their contents recursively

Critical: Always run the test mode first to verify you're targeting the right folders. Accidental deletions are hard to undo!

Python Script (Cross-Platform: Windows/Linux/macOS)

If you need something that works across all operating systems, Python is the way to go. This script uses the os and re modules to scan directories and validate folder names.

import os
import re
import shutil

def remove_non_date_folders(target_dir):
    # Regex to match YYYY_M_D or YYYY_MM_DD format
    date_regex = re.compile(r'^\d{4}_\d{1,2}_\d{1,2}$')
    
    # Loop through all entries in the target directory
    for item in os.scandir(target_dir):
        if item.is_dir() and not date_regex.match(item.name):
            # Skip current/parent dir (scandir usually doesn't include these, but just in case)
            if item.name in ('.', '..'):
                continue
            print(f"Marked for deletion: {item.path}")
            # Uncomment the line below to actually delete the folder
            # shutil.rmtree(item.path)

if __name__ == "__main__":
    # Replace this with your directory path
    target_directory = "/path/to/your/folder"
    remove_non_date_folders(target_directory)

How to use:

  1. Replace target_directory with your actual folder path
  2. Run the script first without uncommenting shutil.rmtree to see which folders will be deleted
  3. Once you're sure, uncomment that line to perform the deletion

Extra Tips

  • Backup First: Always make a copy of your directory before running any deletion scripts. Better safe than sorry!
  • Stricter Validation: If you need to ensure dates are actually valid (e.g., months 1-12, days 1-31), use a more precise regex like:
    ^(19|20)\d{2}_([1-9]|1[0-2])_([1-9]|[12]\d|3[01])$
    
    This limits years to 1900-2099, months 1-12, and days 1-31 (note: it doesn't account for leap years, but that's often unnecessary for folder name checks).

内容的提问来源于stack exchange,提问作者Md. Kamruzzaman Khondakar

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.29 07:07:44