linux - 从文件列表创建 .new 文件

标签 linux bash testing copy diff

我一直在网上搜索 .sh 脚本来执行此操作,但我没有找到。

此刻我有一个脚本,它将使用 find 命令创建一个文件列表。 此文件列表与复制一起使用以将它们复制到另一个文件夹,一切正常。

现在我想创建一个脚本文件,它将获取文件列表并执行以下测试: - 如果目标文件不存在,则复制该文件。 - 如果文件存在于目的地并且与源相同,则不要执行任何操作。 - 如果目标文件存在并且与源文件不同,复制它并将其扩展名更改为 .new

这是将创建文件列表的脚本:

# File source to copy text files
find /home/repo/source -type f -name '*.txt' -o -name '*.cfg' -o -name '*.doc' -o -name '*.lst' -o -name '*.inf' -o -name '*.xml' > ../copy-from.txt
sed -i 's/ /\\ /g' ../copy-from.txt

# File destination to copy text files
find . -type f -name '*.txt' -o -name '*.cfg' -o -name '*.doc' -o -name '*.lst' -o -name '*.inf' -o -name '*.xml' > ../copy-to.txt
sed -i 's/ /\\ /g' ../copy-to.txt
sed -i 's/\(.\{2\}\)//' ../copy-to.txt

# Merge source and destination files and add cp command
paste ../copy-from.txt ../copy-to.txt > ../copy.sh
rm ../copy-from.txt ../copy-to.txt
sed -i 's/^/cp /' ../copy.sh

希望有人能指出我正确的道路或提供一个脚本来完成我正在寻找的事情。

问候

最佳答案

在我看来,您可能必须使用诸如 git 之类的工具。然后,您可以使用两个存储库并在从另一个存储库拉取/合并之前检查提交。

如果您坚持以与您描述的方式类似的方式进行操作,这里有一个小的 bash 脚本可以做到这一点。它一步完成所有工作,即不生成包含要复制的文件列表的临时文件,它只是在源目录中找到所有新的/更改的文件并将它们复制到目标目录,添加一个 。必要时添加新的 后缀。

src='/path/to/source/dir'
dst='/path/to/destination/dir'
find "$src" -type f \( -name '*.txt' -o -name '*.cfg' -o -name '*.doc' -o -name '*.lst' -o -name '*.inf' -o -name '*.xml' \) -printf '%P\0' |
    while IFS= read -r -d '' file; do
        if [[ ! -e "$dst/$file" ]]; then
            cp -a -- "$src/$file" "$dst/$file"
        elif ! cmp --silent "$src/$file" "$dst/$file"; then
            cp -a -- "$src/$file" "$dst/$file.new"
        fi
    done

它使用cmp 来确定两个文件是否相同。这意味着如果涉及的文件很大,它可能会很慢,因为它可能必须读取整个文件。不过对于小的配置文件应该没问题。当然,这是一个 shell 脚本,如果你有很多文件,它可能会很慢,因为它会调用外部程序。

关于linux - 从文件列表创建 .new 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39687846/

相关文章:

linux - CLOCK_MONOTONIC 与 CLOCK_MONOTONIC_RAW 有什么区别?

c - C进程在fork()之后打印两次,即使它在父进程内部并且我刷新了stdout

c - 当 TCP keep-alive 断开连接时,我会得到什么套接字错误?

如果没有按键输入,C# Mono 控制台应用程序将停止输出

python - 如果文件在两台机器中都丢失,如何以非零状态退出 shell 脚本?

c# - NUnit 的奇怪行为,ExpectedException & yield return

Python 和/或 Perl VS bash

bash - 为什么 bash 从字面上使用单引号和双引号?

使用 Jasmine 进行 Angular5 测试。组件是 2 个模块 : AppModule and DynamicTestModule 声明的一部分

testing - Spring 批处理 : Test a JobExecutionListener