Saturday, April 27, 2024
15
rated 0 times [  15] [ 0]  / answers: 1 / hits: 53613  / 2 Years ago, thu, november 25, 2021, 7:40:38

I copied some file from source folder into destination folder by using bellow command line in terminal.



sudo cp From_SOURCE/* To_DESTINATION/


Now I want to undo this command.


More From » command-line

 Answers
3

If I understand well, the following is the case:




  • You copied a (presumably large) number of files on to an existing directory, and you need / want to reverse the action.

  • The targeted directory contains a number of other files, that you need to keep there, which makes it impossible to simply remove all files from the directory



The script below looks in the original (source) directory and lists those files. Then it looks into the directory you copied the files to, and removes only the listed files, as they exist in the source directory.



The try element is added to prevent errors, for example in case you might have removed some files manually already, or if not all files from the source directory were copied to the destination. If you need sudo privileges, simply run the script with "sudo" (see below).



The script



#!/usr/bin/env python

import os

source_dir = "/path/to/source" # the folder you copied the files from
target_folder = "/path/to/destination" # the folder you copied the files to

for root, dirs, files in os.walk(source_dir):
for name in files:
try:
os.remove(target_folder+"/"+name)
except FileNotFoundError:
pass


How to use




  • Paste the script in an empty file, save it as reverse.py,

  • Insert the correct paths for source and target folder,

  • Make it executable for convenience reasons,

  • Run it by the command:



    [sudo] /path/to/reverse.py



Warning



First try on a test directory if I understood well what you need to achieve!






If the sourcedirectory is "flat"



In case the source directory has no sub-directories, the script can even be simpler:



#!/usr/bin/env python

import os

source_dir = "/path/to/source" # the folder you copied the files from
target_folder = "/path/to/destination" # the folder you copied the files to

for file in os.listdir(source_dir):
try:
os.remove(target_folder+"/"+file)
except FileNotFoundError:
pass


Note



If the copy action overwrote (replaced) a similarly named file in the destination, the file will be removed, but the original file will (of course) not be brought back by the script. The assumption is that there are no name clashes.


[#23723] Friday, November 26, 2021, 2 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
coffekne

Total Points: 114
Total Questions: 122
Total Answers: 126

Location: Mauritania
Member since Sun, Oct 17, 2021
3 Years ago
;