1

给定文件夹将有子文件夹。每个子文件夹应该有 36 个具有以下模式的文件:(<subfoldername>_<xx>.png例如 abc_09.png、abc_10.png 等)如果缺少 36 个文件(01 到 36)中的任何一个,则通过复制 1x1.png 作为该文件在该文件夹中创建它,例如,如果 abc_01.png 丢失,则将 1x1.png 作为 abc_01.png 复制到该子文件夹中,这样最后每个子文件夹都应包含所有 36 个编号的文件。假设 1x1.png 的硬编码位置。

到目前为止,我能够做到这一点:

#!/bin/bash

#list all sub directories and files under it
if [ ! -z "$1" ] 
  then
    echo "Arguments passed";
    if [ -d "$1" ]
    then    
        tree -if --noreport "$1";
    else        
        echo "Supplied argument is not a directory";
    fi
else
    echo "No arguments passed";
fi

但我不知道如何前进。

4

2 回答 2

4
DEFAULT_PNG='/path/to/your/1x1.png'

if [[ $1 ]]; then
    echo "Arguments passed";

    if [[ -d $1 ]]; then    

        for curFile in "$1/"abc_{01..36}.png; do
            if ! [[ -f $curFile ]]; then
                cp -- "$DEFAULT_PNG" "$curFile"
            fi
        done

    else        
        echo 'Supplied argument is not a directory';
    fi
else
    echo 'No arguments passed';
fi

阅读有关bash 大括号扩展的信息

在你编辑了你的问题之后,我开始明白你想要一些不同的东西......所以,如果我这次做对了,这里有一个适用于子文件夹的脚本

DEFAULT_PNG='/path/to/your/1x1.png'

if [[ $1 ]]; then
    echo "Arguments passed";
    if [[ -d $1 ]]; then

        for curSubdir in "$1/"*; do 
            if [[ -d $curSubdir ]]; then #skip regular files
                dirBasename=$(basename -- "$curSubdir")
                for curFile in "$curSubdir/$dirBasename"_{01..36}.png; do
                    if ! [[ -f $curFile ]]; then
                        cp -- "$DEFAULT_PNG" "$curFile"
                    fi
                done

            fi
        done

    else        
        echo 'Supplied argument is not a directory'
    fi
else
    echo 'No arguments passed'
fi
于 2013-08-30T13:08:02.123 回答
1

我知道已经接受了一个很好的答案,但是我对这个问题的初步阅读意味着 givenFolder 的子文件夹可能会向下延伸到更任意的深度,并且脚本的直接参数(“givenFolder”)不填充 PNG 文件。所以这就是它的样子。

并感谢@Aleks-Daniel 提醒我使用 bash 的漂亮大括号扩展。

#!/bin/bash

[ $# -ge 1 ] || exit 0

DEF_PNG='/tmp/1x1.png'

[ -f "$DEF_PNG" ] || ppmmake black 1 1 | pnmtopng > "$DEF_PNG" || exit 1

function handle_subdir() {
  [ -d "$1" ] || return

  local base=$(basename "$1")
  local png

  for png in "$1"/"$base"_{01..36}.png; do
    [ -e "$png" ] || cp "$DEF_PNG" "$png"
  done
}

# Only process subdirectories of the directory arguments to
# the script, but do so to an arbitray depth.
#
find "$@" -type d -mindepth 1 | while read dir; do handle_subdir "$dir"; done

exit $?

如果子文件夹由对手创建并包含 \n 字符,则将 find 输出管道传输到 bash 的 read 命令将产生不良行为。但是,快速测试表明它可以正确处理文件夹/目录名称中的其他特殊字符(空格、$、* 等)。

于 2013-08-30T15:54:04.437 回答