Macos 克隆目录和交换映像 我有一个包含html文件和一个图像文件的目录 我有第二个目录,其中有几十个图像文件

Macos 克隆目录和交换映像 我有一个包含html文件和一个图像文件的目录 我有第二个目录,其中有几十个图像文件,macos,bash,shell,terminal,Macos,Bash,Shell,Terminal,对于第二个目录中的每个映像,我需要克隆整个第一个目录,并用第二个目录中的映像替换该目录中的映像。以及更改对html文件中第一个图像的引用 因此,在此之前: root │ ├───foo │ ├───index.html │ └───lorem.png │ ├───images │ ├───ipsum │ ├───dolor │ ├───sit │ ├───amet │ ├───consectetur │ └───adipiscing 然后: root │ ├──

对于第二个目录中的每个映像,我需要克隆整个第一个目录,并用第二个目录中的映像替换该目录中的映像。以及更改对html文件中第一个图像的引用

因此,在此之前:

root
│
├───foo
│   ├───index.html
│   └───lorem.png
│
├───images
│   ├───ipsum
│   ├───dolor
│   ├───sit
│   ├───amet
│   ├───consectetur
│   └───adipiscing
然后:

root
│
├───foo
│   ├───index.html
│   └───lorem.png
│
├───foo-ipsum
│   ├───index.html
│   └───ipsum.png
│
├───foo-dolor
│   ├───index.html
│   └───dolor.png
│
├───foo-sit
│   ├───index.html
│   └───sit.png
│
├───foo-amet
│   ├───index.html
│   └───amet.png
│
├───foo-consectetur
│   ├───index.html
│   └───consectetur.png
│
├───foo-adipiscing
│   ├───index.html
│   └───adipiscing.png

在伪代码中,尝试以下操作:

# for each image
for file in images; do
    # get base name: i.e. image.png -> image
    base=$(echo $file | sed 's/.png//')
    # create desired dir foo.image
    mkdir "foo-${base}"
    # copy correct stuff to the dir
    cp index.html "foo-${base}/"
    mv "images/$file" "foo-${base}/"
end
# remove image dir
rmdir images/
当您遇到问题时,请发布更多详细信息,我们很乐意为您提供帮助。您基本上只需要构造一个语法正确的for循环


提示:您可以使用
$(ls dir)
(不建议)在文件名上循环,也可以将
find
命令与
exec
选项结合使用(首选)。然后,您可以将4个命令放在bash函数的循环中,并使用find的exec调用它。

我编写了这个脚本,它完全满足您的需要,包括修改html文件。调用脚本时,必须在示例“foo”中提供“template dir”的名称作为参数:
bash script.bash foo

#!/bin/bash

[[ $# -eq 1 ]] || {
    echo "You MUST provide the template dir as a parameter."
    exit -1
}

[[ -d $1 ]] || {
    echo "The template directory ($1) doesn't exist!"
    exit -1
}

template="$1"
template_img="$(ls $template | grep \.png)"
regex="(.*)\.png"

for f in $(ls images); do
    [[ $f =~ $regex ]] || continue

    name="${BASH_REMATCH[1]}"
    mkdir $name && {
        cp $template/index.html images/$f $name
        sed -i -e "s/$template_img/${name}.png/"  $name/index.html
    }
done

加号1表示你的问题有很好的视觉清晰度,减号1表示你没有试图解决你的问题。Stackoverflow不是一个免费的编码服务,您需要展示解决问题的尝试,并包含测试中的相关错误消息。祝你好运。另外,如果你是认真的,你必须用
/bin/sh
,请为你的操作系统添加一个标签,或者解释你想要一个完全向后兼容的解决方案。对不起,我只是一个设计师,我真的不知道从哪里开始。我一直在手动执行此操作,但找不到类似描述的问题来解决。当您使用OSX时,您并不真正想使用
sh
。将标签更改为
bash
,您可能会收到更多反馈。祝你好运。为什么不建议使用
$(ls dir)
?我发现它比
find
alternative要干净得多。@gdrooid:1。因为如果文件名包含空格(或glob),它会失败得很惨;2.因为它生成一个子shell并派生一个外部命令;3.因为
ls
的输出是人类可读的,因此不是机器可读的;4.因为使用Bash的glob机制更简单、更短、更安全。这里有很多不好的东西:让我们从最重要的东西开始:不要解析
ls
的输出,使用更多的引号。非常感谢!这对我来说非常合适。现在我有点接近了解所有这些东西了。