从路径列表创建目录列表,并在每个目录中创建一个空白文本文件

从路径列表创建目录列表,并在每个目录中创建一个空白文本文件

输入是路径列表。除第一个目录之外的所有内容都应被忽略/删除。

例如,名为 dirnames 或 dirs 的文本文件输入以下 3 行文本:

/how-to-blah-blah/
/how-to-blah-blah-blah/
/how-to-blah-blah-blah/

运行脚本时,将创建名为的目录和文件

/how-to-blah-blah/file.txt
/how-to-blah-blah-blah/file.txt
/how-to-blah-blah-blah/file.txt

或者

输入

"/d1","d2/subd1/subd2","d3/subder1/","d3/subder1/file.jpg"

输出:

应创建 4 个名为 d1 d2、d3 和 d4 的目录,并且应在每个目录下创建一个名为 file.txt 的文件

三次尝试。它们都不能完全工作。

第一次尝试

for i in ${a[@]}
do
    folder=`dirname $i`
while [ "${folder:0:1}" = "/" ]
do
    folder=${folder:1}
done
echo -p $folder
done

for i in *
do
    if [ -d $i ]
    then
        touch ./$i/index.html
    fi
done

第二次尝试

import os
from file (replace with actual file name)
with open('directory_list.txt', 'r') as f:
dir_list = f.read().split(',')

for dir_name in dir_list:

dir_name = dir_name.strip().strip('/')

if '/' not in dir_name:
    os.makedirs(dir_name, exist_ok=True)
    open(os.path.join(dir_name, 'blank_file.txt'), 'w').close()

第三次尝试

import os

def create_directories_and_files(directory_list):
    for directory in directory_list:
        if not os.path.exists(directory):
            os.makedirs(directory)
    
        file = os.path.join(directory, "blank_file.txt")
        open(file, 'w').close()


directories = ["dir1", "dir2", "dir3"]
create_directories_and_files(directories)

答案1

你可以在 bash 中做这样的事情,但我不确定它的可靠性。你可以尝试的一件事是

#!/usr/bin/env bash

while IFS=',' read -ra dirs
  do for dir in "${dirs[@]}"
     do tmp="${dir//\"/}" # Get rid of double quotes
        tmp="${tmp#/*}" # Remove forward slash if it is somewhere in front of the string
        tmp="${tmp%%/*}" # Remove everything after the first `/` including
        mkdir -p "$tmp" && touch "$tmp/emptyfile"
     done
  done < dirs.csv

这里我们使用字符串操作来切割和压缩来自 csv 的字符串。

看看这是否有帮助

答案2

我已经用Java编写了解决方案。它将使用opencsv库从 CSV 文件读取路径。

CSV 输入文件示例:

在此输入图像描述

之后,从文件加载所有路径,它将删除一些不必要的东西:

  • 双斜杠
  • 空字符串

这是我的java代码:

// get user directory in your home pc
    File homeDir = new File(System.getProperty("user.home"));

// read CSV file as input
Reader reader = Files.newBufferedReader(Paths.get("inputPaths.csv"));

// read back slash also
CSVParser parser = new CSVParser(CSVParser.DEFAULT_SEPARATOR, CSVParser.DEFAULT_QUOTE_CHARACTER, '\0', CSVParser.DEFAULT_STRICT_QUOTES);

// skip 1 first line in 2nd parameter
CSVReader csvReader = new CSVReader(reader, 1, parser);

// load everything in CSV file
List<String[]> records = csvReader.readAll();
for (String[] record : records) {
    // replace double slashes from a path
    String newString = record[0].replaceAll("//", "/");
    // split path on forward slashes
    String[] folders = newString.split("/");
    String path = homeDir + "\\direcotories";
    for (String folder : folders) {
        // check if path is not empty and not contains a dot character
        if (!folder.isEmpty() && !folder.contains(".")) {
            path += ("\\" + folder); // concatenate complete path
        }
    }
    File theDir = new File(path);
    try {
        if (theDir.mkdirs()) { // create directories
            File emptyFile = new File(theDir, "\\file.txt");
            if (emptyFile.createNewFile()) { // create an empty file
                System.out.println("File created: " + emptyFile.getPath());
            } else {
                System.out.println("File already created: " + emptyFile.getPath());
            }
        }
    } catch (IOException e) {
        System.out.println(e.getMessage());
    }
}

输出截图:

在此输入图像描述

创建目录截图

在此输入图像描述

答案3

#!/bin/bash

file="dirnames"

while read line
do
    while [ "${line:0:1}" = "/" ]
    do
        line=${line:1}
    done
    mkdir -p $line
done < $file

for i in *
do
    if [ -d $i ]
    then
        touch ./$i/file.txt
    fi
done

相关内容