如何将文本文件中指定的文件移动到 BASH 上的另一个目录?

Wey*_*van 6 bash text-processing file-management mv

我有一个包含 400 多个图像的目录。他们中的大多数都是腐败的。我确定了好的。它们列在一个文本文件中(有 100 多个)。如何一次将它们全部移动到 BASH 上的另一个目录?

iga*_*gal 8

有几种方法可以立即想到:

  1. 使用while循环
  2. 使用 xargs
  3. 使用 rsync

假设文件名被列出(每行一个)files.txt,我们想将它们从子目录移动source/到子目录target

while 循环可能如下所示:

while read filename; do mv source/${filename} target/; done < files.txt
Run Code Online (Sandbox Code Playgroud)

xargs 命令可能如下所示:

cat files.txt | xargs -n 1 -d'\n' -I {} mv source/{} target/
Run Code Online (Sandbox Code Playgroud)

rsync 命令可能如下所示:

rsync -av --remove-source-files --files-from=files.txt source/ target/
Run Code Online (Sandbox Code Playgroud)

创建一个沙箱来试验和测试每种方法可能是值得的,例如:

# Create a sandbox directory
mkdir -p /tmp/sandbox

# Create file containing the list of filenames to be moved
for filename in file{001..100}.dat; do basename ${filename}; done >> /tmp/sandbox/files.txt

# Create a source directory (to move files from)
mkdir -p /tmp/sandbox/source

# Populate the source directory (with 100 empty files)
touch /tmp/sandbox/source/file{001..100}.dat

# Create a target directory (to move files to)
mkdir -p /tmp/sandbox/target

# Move the files from the source directory to the target directory
rsync -av --remove-source-files --files-from=/tmp/sandbox/files.txt /tmp/sandbox/source/ /tmp/sandbox/target/
Run Code Online (Sandbox Code Playgroud)