已知可批量创建目录,如何同时创建目录及其中文件并批量执行?
Hey there! Let's break this down into straightforward steps—first handling a single directory + file combo, then scaling it up for batches. I’ll cover both Bash (for Linux/macOS/WSL) and PowerShell (for Windows) since those are the most common tools for this kind of task.
Bash (Linux/macOS/WSL)
To create a directory and immediately add a file inside it in one line, use:
mkdir my_new_dir && touch my_new_dir/empty_file.txt
mkdir my_new_dircreates the directory&&ensures the next command only runs if the directory was created successfullytouchmakes an empty file. If you want to add initial content right away, swaptouchwith an echo command:mkdir my_new_dir && echo "First line of content" > my_new_dir/notes.txt
PowerShell (Windows)
For Windows, use these commands to make a directory and file:
New-Item -ItemType Directory -Path "my_new_dir"; New-Item -ItemType File -Path "my_new_dir\empty_file.txt"
Or use shorter aliases for quicker typing:
mkdir my_new_dir; ni my_new_dir\empty_file.txt
To add content to the file immediately:
mkdir my_new_dir; "First line of content" | Out-File -Path "my_new_dir\notes.txt"
If you already know the list of directories you want to create, or need to generate a sequence of directories, here’s how to automate the whole process.
Bash (Linux/macOS/WSL)
Option 1: Use a pre-defined list of directories
Create a text file (e.g., dirs.txt) where each line is a directory name:
project_alpha project_beta project_gamma
Then run this loop to create each directory and a file inside it:
while read dir; do # -p ensures we don't get errors if the directory already exists mkdir -p "$dir" && touch "$dir/readme.md" # Optional: Add custom content to the file echo "This is the readme for $dir" > "$dir/readme.md" done < dirs.txt
Option 2: Generate a sequence of directories
If you need directories like task_1, task_2, ..., task_10, use a for loop:
for i in {1..10}; do dir_name="task_$i" mkdir -p "$dir_name" && echo "Task $i: Initial setup complete" > "$dir_name/status.txt" done
PowerShell (Windows)
Option 1: Use a pre-defined list of directories
Create a dirs.txt file with one directory name per line, then run:
Get-Content dirs.txt | ForEach-Object { $dirPath = $_ # -Force skips errors if the directory already exists New-Item -ItemType Directory -Path $dirPath -Force New-Item -ItemType File -Path "$dirPath\readme.md" -Value "Welcome to $dirPath" }
Option 2: Generate a sequence of directories
To make task_1 through task_10 with files inside each:
1..10 | ForEach-Object { $dirName = "task_$_" New-Item -ItemType Directory -Path $dirName -Force "Task $_: Ready for work" | Out-File -Path "$dirName\status.txt" }
内容的提问来源于stack exchange,提问作者Ovid Virgil

