移动时附加而不是覆盖文件

时间:2010-03-27 13:17:25

标签: linux bash command-line

我有以下目录结构:

+-archive
  +-a
    +-data.txt
  +-b
    +-data.txt 
+-incoming
  +-a
    +-data.txt
  +-c
    +-data.txt

如何处理mv incoming/* archive/的等效内容,但incoming中的文件内容是否附加到archive中,而不是覆盖它们?

3 个答案:

答案 0 :(得分:2)

# move to incoming/ so that we don't
# need to strip a path prefix
cd incoming

# create directories that are missing in archive
for d in `find . -type d`; do
  if [ ! -d "../archive/$d" ]; then
    mkdir -p "../archive/$d"
  fi
done

# concatenate all files to already existing
# ones (or automatically create them)
for f in `find . -type f`; do
  cat "$f" >> "../archive/$f"
done

这应找到incoming中的任何文件,并将其连接到archive中的现有文件。

重要的部分是里面 incoming,因为否则我们必须去除路径前缀(这是可能的,但在上面的情况下是不必要的)。在上述情况下,$f的值通常看起来像./a/data.txt,因此重定向会转到../archive/./a/data.txt

答案 1 :(得分:0)

以下是适当引用的版本:

#!/bin/sh
if [ -z "$1" ]; then
    # acting as parent script
    find incoming -type f -exec "$0" {} \;
else
    # acting as child script
    for in_file; do
        if [ -f "$in_file" ]; then
            destfile="${in_file/incoming/archive}"
            test -d "$(dirname "$destfile")" || mkdir -p "$_"
            cat "$in_file" >> "$destfile" &&
            rm -f "$in_file"
        fi
    done
fi

答案 2 :(得分:0)

在当前目录中运行它。

find ./incoming  -type f | while read -r FILE
do
  dest=${FILE/incoming/archive}
  cat "$FILE" >> "$dest"
done

incoming/c中的那个不会附加