我想将多个文件从一个目录复制并重命名到另一个目录。特别是,我想要这样的东西:
/tmp/tmp.XXX/aaa.original.txt
/tmp/tmp.XXX/bb5.original.txt
/tmp/tmp.XXX/x2x.original.txt
复制到
/root/hello/dump-aaa.txt
/root/hello/dump-bb5.txt
/root/hello/dump-x2x.txt
我尝试过一些类似的方法,但不起作用:
cp /tmp/tmp.XXX/*.original.txt /root/hello/*.txt
find /tmp/tmp.XXX/ -name '*.original.txt' | xargs -i cp /root/hello/dump-{}.txt
for f in /tmp/tmp.XXX/*.original.txt; do cp -- "$f" "/root/hello/dump-$f.txt"; done
通常上述代码的结果是错误:
cp: cannot create regular file '/root/hello/dump-/tmp/tmp.XXX/aaa.original.txt.txt': No such file or directory
答案1
bash
解决方案:
for f in /tmp/tmp.XXX/*.original.txt; do
bn="${f##*/}" # extracting file basename
cp "$f" "/root/hello/dump-${bn%%.*}.txt"
done