简体   繁体   中英

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).

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.

In either case I'm not familiar with writing loops in bash, so any help would be much appreciated! (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. dirname extracts the dir from a file path.

References:

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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