Reputation: 566
I have multiple sources folder(these folders have a lot of files named such as ip address Ex: 192.168.2.1
), I want to merge them in a target folder.
What is the ways of doing this operation on a Linux using terminal.
Source 1
/Desktop/source1/192.168.2.1
/Desktop/source1/192.168.2.2
/Desktop/source1/192.168.2.3
Source 2
/Desktop/source2/192.168.2.1
/Desktop/source2/192.168.2.2
/Desktop/source2/192.168.2.3
Source 3
/Desktop/source2/192.168.2.1
Source 4
Source 5
Source 6
.
.
.
Target
/Desktop/target/192.168.2.1
/Desktop/target/192.168.2.2
/Desktop/target/192.168.2.3
/Desktop/target/192.168.2.1.copy
/Desktop/target/192.168.2.2.copy
/Desktop/target/192.168.2.3.copy
/Desktop/target/192.168.2.1.copy.copy
original files have no file extension I just named them as what they are but I am opening them in gedit or any text editor. The duplicated file suffix might be ('192.168.2.3.copy or 192.168.2.3_2 or anything just needs to be different)
What is the way of doing this operation with cp command, shell script or any other command in Linux?
Upvotes: 0
Views: 5764
Reputation:
The answer by Munir is perfect. My reputation is too low to comment on his solution, but I would like to mention on it why this works:
cp -f --backup --suffix='.copy' source2/* target/
Normally --backup will backup the file in the target folder, by appending a "~" at the end. The suffix option changes the "~" with copy. So why does this solution change the name of the source file and not the target? It's the addition of the -f option in the line, which is a radically different behavior than what -f normally does. This is documented in the last paragraph of the man page:
As a special case, cp makes a backup of SOURCE when the force and backup options are given and SOURCE and DEST are the same name for an existing, regular file.
Upvotes: 1
Reputation: 3612
cp source1/* target/
cp -f --backup --suffix='.copy' source2/* target/
Just note that this will not add .copy
suffix to any files that are in source2
but not in source1
. That is, .copy
will only be added for duplicate file names.
For multiple source folders, you can do something like:
cp source1/* target/
for i in {2..n} ; do
cp -f --backup=numbered source${i}/* target/
done
Replace n
with the your folder number. This will put a .~1~
for the first copy, .~2~
for the second copy and so on.
Upvotes: 1