Som*_*ict 178 command-line files
我有一个很大的图片文件夹(数千张),我有很长的文件列表,按确切的文件名,我需要将它们复制到另一个文件夹。我想知道是否有办法可以从该文件夹中按名称选择多个特定文件,然后使用终端将它们复制到另一个文件夹,而无需单独复制它们?
Bry*_*yan 255
有几种方法可以实现这一点。我见过的最简单的方法是使用以下方法。
cp /home/usr/dir/{file1,file2,file3,file4} /home/usr/destination/
Run Code Online (Sandbox Code Playgroud)
语法使用 cp 命令,后跟所需文件所在目录的路径,您希望复制的所有文件都用括号括起来并用逗号分隔。
请务必注意文件之间没有空格。命令的最后一部分/home/usr/destination/是您希望将文件复制到的目录。
或者如果所有文件都具有相同的前缀但不同的结尾,您可以执行以下操作:
cp /home/usr/dir/file{1..4} ./
Run Code Online (Sandbox Code Playgroud)
将复制文件 1、文件 2、文件 3 和文件 4 的位置。
从你对问题的措辞来看,我相信这就是你正在寻找的,但听起来你可能正在寻找一个命令来读取文件列表并将它们全部复制到某个目录。如果是这种情况,请告诉我,我会编辑我的答案。
所以我写了一个小python脚本,我相信它应该可以完成工作。但是,我不确定您对 Python 的精通程度(如果精通的话),因此我将尝试尽可能地解释如何使用此脚本,并请根据您的需要提出尽可能多的问题。
cp /home/usr/dir/{file1,file2,file3,file4} /home/usr/destination/
Run Code Online (Sandbox Code Playgroud)
这个脚本使用起来应该比较简单。首先,将上述代码复制到程序 gedit(应该在 Ubuntu 中预装)或任何其他文本编辑器中。
完成后,将文件作为move.py保存在您的主目录中(它可以是任何目录,但为了便于说明,我们只使用主目录)或将文件所在的目录添加到您的 PATH 中。然后cd从终端到您的主目录(或您保存 move.py 的任何目录)并键入以下命令:
python move.py /path/to/src/ /path/to/dst/ file.txt
Run Code Online (Sandbox Code Playgroud)
这应该将所有从源目录列出的文件复制到目标目录,并复制格式为 pic(1).jpg、pic(2).jpg 等。 file.txt应该是一个文件,其中列出了您要复制的所有图片,每个条目都在单独的一行中。
此脚本绝不会影响源目录,但只需确保输入源目录和目标目录的正确路径,最糟糕的情况是将文件复制到错误的目录。
/源Ros*_*len 85
也许我遗漏了您问题的一个细节,但给出的答案似乎过多。如果您想要命令行解决方案而不是脚本,为什么不:
cd /path/to/src/
cp -t /path/to/dst/ file1 file2 file3 ...
Run Code Online (Sandbox Code Playgroud)
这样做的好处是你可以用 tab 完成文件名
这是一个纯粹的 bash 解决方案。它将从输入文件中读取文件名(每行一个)并复制每个文件名,重命名重复项。
#!/usr/bin/env bash
## The destination folder where your files will
## be copied to.
dest="bar";
## For each file path in your input file
while read path; do
## $target is the name of the file, removing the path.
## For example, given /foo/bar.txt, the $target will be bar.txt.
target=$(basename "$path");
## Counter for duplicate files
c="";
## Since $c is empty, this will check if the
## file exists in target.
while [[ -e "$dest"/"$target"$c ]]; do
echo "$target exists";
## If the target exists, add 1 to the value of $c
## and check if a file called $target$c (for example, bar.txt1)
## exists. This loop will continue until $c has a value
## such that there is no file called $target$c in the directory.
let c++;
target="$target"$c;
done;
## We now have everything we need, so lets copy.
cp "$path" "$dest"/"$target";
done
Run Code Online (Sandbox Code Playgroud)
将此脚本保存在您的文件夹中$PATH,并使用路径列表作为输入调用它:
auto_copy.sh < file_paths.txt
Run Code Online (Sandbox Code Playgroud)
您还可以从终端以命令的形式运行整个过程:
auto_copy.sh < file_paths.txt
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
638269 次 |
| 最近记录: |