如何使用 shell 脚本从命令提示符将目录中现有的特定文件复制到新创建的子目录中

如何使用 shell 脚本从命令提示符将目录中现有的特定文件复制到新创建的子目录中

我在尝试将一个预先存在的文件(特别是 java)从当前目录复制到子目录(以及根据命令将一些副本复制到其子目录等)时遇到了一些小问题,我知道这听起来很简单,但当我们深入了解细节时,它会变得有点复杂(至少对我来说)。

例如,我们有一个目录:

├── Main
│   ├── Initial.java                  # Initial java file that was already there
│   ├── Then.java                     # Then java file that was already there

这里我们有一个根据说明在终端中输入的内容的示例:

./Code NewSubDir1.NewSubDir2.Initial NewSubDir1.Then

其中 Code 是 .sh 文件名。每个参数都应该是目录路径,直到我们得到文件名,在这种情况下,我们将有最初的然后

以下是预期的输出:

├── Main
│   ├── Initial.java                  # Initial java file that was already there
│   ├── Then.java                     # Then java file that was already there
│   ├── NewSubDir1.                   # Newly Created Subdirectory from command
│   │   ├── Initial.java              # Copied java file from Initial.java
│   │   ├── NewSubDir2                # Newly Created Subdirectory from command
│   │   │   ├── Then.java             # Copied java file from Then.java

以下是我迄今为止尝试过的方法:

我已经编写了如何获取子目录的代码,所以我有

├── Main
│   ├── Initial.java                  # Initial java file that was already there
│   ├── Then.java                     # Then java file that was already there
│   ├── NewSubDir1.                   # Newly Created Subdirectory from command
│   │   ├── NewSubDir2                # Newly Created Subdirectory from command

现在,进入复制部分有点棘手:

# An array of the arguments
declare -a directory
IFS=' ' read -r -a directory <<< "$*"

# Pre-existing java files
javaFiles=($(ls *.java))


for (( i=0 ; i < ${args} ; i++ ))
do
            # Get wanted filename from command prompt (EXAMPLE: Initial)
            copyFile=${directory[i]##*.}

            dir=${directory[i]%.*}
            path=${dir//[.]//}
            echo $path

            for (( j=0 ; j < ${#javaFiles} ; j++ ))
            do

                javaName=${javaFiles[j]%%.*}

                if [[ "${javaFiles[$j]}" == "${copyFile[$i]}" ]]
                then

                    # I know this part is wrong, but I hope this will give an idea on what I'm trying to do
                    cp "${javaFiles[j]}" "$path"
                fi
            done
            
            # Other code is not shown
done

相关内容