#!/bin/bash
prev='placeholder'
filename='mkDir.txt'
echo "Starting mkDir script using mkDir.txt."
while IFS=' ' read line || [[ -n "$line" ]]; do
echo "creating dir : $line"
if [[ ${line:0:1} == [[:space:]] ]]
then
cd $prev
mkdir $line
cd '..'
else
mkdir $line
fi
prev=$line
done < $filename
这是我目前的脚本。但它不会像我想要的那样创建子目录。我理想的文本文件如下所示:
tester
test
test2
标签/空格应该表明这是一个子目录。我怎样才能让它发挥作用?
答案 0 :(得分:0)
就个人而言,我宁愿使用AWK程序从输入文件生成bash脚本,然后运行bash脚本:
#!/bin/awk
# WARNING: this example assumes there are is no whitespace in the directory names!
BEGIN { parentdir = "." }
/^[[:space:]]*$/ { next }
/^[[:space:]]/ { print "mkdir " parentdir "/" $1; next }
{ parentdir = $1; print "mkdir " parentdir }
这样调用AWK:awk -f file-with-code-from-above mkDir.txt
内容为
的文件mkDir.txt subdir
dir1
subdir
dir2
subdir
会产生输出
mkdir ./subdir
mkdir dir1
mkdir dir1/subdir
mkdir dir2
mkdir dir2/subdir
答案 1 :(得分:0)
#!/bin/bash -
function join { local IFS="$1"; shift; echo "$*"; }
branch=()
while IFS=/ read -r -a parts; do
level=${#parts[@]}
branch=( ${branch[@]:0:$level} )
(( --level ))
branch[$level]="${parts[$level]}"
mkdir -p $(join / "${branch[@]}")
done < <(sed -e 's~\t~/~g' input.txt)
join
函数使用$2 .. $*
separator $1
个参数
sed
命令用input.txt
file sed
命令的输出通过process substitution while
循环
IFS
是field separator ${branch[@]:0:$level}
从branch
到0
提取$level - 1
个数组项目在PHP中
<?php
$branch = [];
$fp = fopen('php://stdin', 'r');
while ($line = fgets($fp)) {
$parts = explode("\t", $line);
$level = count($parts);
$branch = array_slice($branch, 0, $level);
$branch[$level - 1] = trim($parts[$level - 1]);
mkdir(implode('/', $branch), 0755, true);
}
fclose($fp);
用法:
php script.php < input.txt