I'd like to merge the content of these folders with a command line.
.
├── folder1
│ │ file.txt
│
├── folder2
│ │ file.txt
│
└───folder3
│ file.txt
How can I do this ?
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems. It only takes a minute to sign up.
Sign up to join this communityFinally I can do this with cp
and its --backup
flag.
cp --backup=numbered */*.txt new_directory/
The following command-line loop will copy the (top-level) contents of every folder named "folder*" in your current directory into a directory named "new_directory". The /*
glob will, by default, not match "dot files"; use shopt -s dotglob
if you want to change that behavior. If the same (base) filename already exists in new_directory, then it prefixes the destination file with the originating folder (and an underscore), in order to make it unique.
All in one line:
for f in folder*/*; do [ ! -e "new_directory/$(basename "$f")" ] && { cp "$f" new_directory/; continue; }; [ -e "new_directory/$(basename "$f")" ] && cp "$f" "new_directory/$(dirname "$f")_$(basename "$f")"; done
Broken out for readability:
for f in folder*/*
do
[ ! -e "new_directory/$(basename "$f")" ] && { cp "$f" new_directory/; continue; }
[ -e "new_directory/$(basename "$f")" ] && cp "$f" "new_directory/$(dirname "$f")_$(basename "$f")"
done
If you intent instead to move the files from their original locations, simply change the cp
's to mv
's.
.txt
files into one directory ?