简体   繁体   English

将多个文件从文件夹移动到目录列表(撤消移动命令)

[英]Move multiple files from a folder to list of directories (Undo a move command)

I want to undo a move command that I did by moving back all the files in a folder ("MySourceDir") to corresponding paths specified in a .txt file ("ListOfFilePaths.txt). 我想通过将文件夹(“ MySourceDir”)中的所有文件移回到.txt文件(“ ListOfFilePaths.txt”)中指定的相应路径来撤消执行的移动命令。

For eg.: 例如:

MySourceDir

File1.txt
File2.txt
File3.txt
.
.
.

I have a text file containing the file paths for each of these files, indicating the directories they were originally in and thus, need to be moved back to. 我有一个文本文件,其中包含每个文件的文件路径,指示它们最初位于的目录,因此需要移回该目录。

ListOfFilePaths.txt

/path/to/dirA/File1.txt
/path/to/dirB/File2.txt
/path/to/dirC/File3.txt

I could probably do this in two ways. 我可能可以通过两种方式做到这一点。 Write a loop to 1) grep the directory path for each file and then move it to the corresponding grepped directory path OR 2) remove the "File#.txt" portion from the directory path and then do a mv command for each file in the list such that the nth file is moved to the nth directory. 写一个循环到1)grep每个文件的目录路径,然后将其移动到相应的grepped目录路径,或者2)从目录路径中删除“ File#.txt”部分,然后对文件中的每个文件执行mv命令列表,以便将第n个文件移动到第n个目录。

In either case I'm not familiar with writing loops in bash, so any help would be much appreciated! 无论哪种情况,我都不熟悉用bash编写循环,因此非常感谢您的帮助! (Similarly, would also appreciate a command to copy these files back to the original folder instead of moving them, keeping the timestamp unchanged :-) ) (类似地,还希望使用命令这些文件复制回原始文件夹,而不是移动它们,从而使时间戳保持不变:-))

From what I understand, you need to: 据我了解,您需要:

  • Loop through the text file 循环浏览文本文件
  • Get the line, extract the text after the final slash (to give you the file name) 得到这一行,在最后的斜杠后提取文本(为您提供文件名)
  • Get the destination dir from the line 从该行获取目标目录
  • Copy the file from the source dir to the dest dir 将文件从源目录复制到目标目录

The code below should help: 下面的代码应该有所帮助:

while read line; do
     fileName=$(basename $line)
     dirName=$(dirname $line)
     cp SourceDir/"$fileName" "$dirName"
done < ListOfFilePaths.txt

basename extracts the filename from a file path. basename从文件路径中提取文件名。 dirname extracts the dir from a file path. dirname从文件路径中提取目录。

References: 参考文献:

https://ss64.com/bash/dirname.html https://ss64.com/bash/dirname.html

https://linux.die.net/man/1/basename https://linux.die.net/man/1/basename

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM