Adding, but not rewriting files when moving

I have the following directory structure:

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

How to make an equivalent mv incoming/* archive/, but add the contents of files in incomingto files in archive, rather than overwrite them?

+3
source share
3 answers
# 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

This should find any file in incomingand merge it into an existing file in archive.

The important part is to be inside incoming, because otherwise we would have to cut the path prefix (which is possible, but unnecessary in this case). In the above case, the value $fusually looks like ./a/data.txt, and therefore the redirect goes to ../archive/./a/data.txt.

+2

:

#!/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
0

run it in the current directory.

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

what incoming/cwill not be added though

0
source

Source: https://habr.com/ru/post/1738775/


All Articles