考虑包含这些文件的folderA:
foo
bar
baz
和文件夹B包含那些:
foo
baz
foobar
qux
如何将foo
和baz
从文件夹 A 复制到新文件夹 C?
请注意,我仅比较它们的名称,而不是它们的内容。
答案1
对文件使用 for 循环。参数扩展可用于提取部分路径:
#! /bin/bash
for file in folderA/* ; do
basename=${file##*/}
if [[ -f folderB/$basename ]] ; then
cp "$file" folderC/"$basename"
fi
done
您也可以循环遍历folderB 中的文件,如果folderB 包含的文件明显少于folderA,我建议您这样做。
答案2
这在我的 bash 中有效:
echo "Folder A"
ls -l ./foldera/
echo "Folder B"
ls -l ./folderb/
echo "Folder C"
ls -l ./folderc/
read -p "Press any key to start"
duplicates=( "$(find foldera folderb -type f -exec basename {} \; |sort |uniq -d)" )
for file in ${duplicates[@]}; do
cp "./foldera/$file" "./folderc/$file"
done
echo "Script Finish. Folder C"
ls -l ./folderc/
输出:
root@debian:# ./bashtest.sh
Folder A
total 32
-rw-r--r-- 1 root root 8230 Oct 14 01:36 abp.png
-rwxr-xr-x 1 root root 8805 Dec 9 01:58 appslist.sh
-rwxrwxrwx 1 root root 2682 Nov 14 02:50 cpu.sh
-rw-r--r-- 1 root root 898 Oct 11 00:25 tkinter-3.py
Folder B
total 24
-rw-r--r-- 1 root root 8230 Oct 14 01:36 abp.png
-rw-r--r-- 1 root root 898 Oct 11 00:25 tkinter-3.py
-rwxr-xr-x 1 root root 595 Oct 28 00:02 yadlist.sh
-rwxr-xr-x 1 root root 2455 Nov 16 01:24 yadnotebook.sh
Folder C
total 0
Press any key to start
Script Finish. Folder C
total 16
-rw-r--r-- 1 root root 8230 Dec 18 23:55 abp.png
-rw-r--r-- 1 root root 898 Dec 18 23:55 tkinter-3.py