0

Consider my root dir ls gives the following output:

1  2  3  4  a  b  c  d

Some files and some dirs. I want to remove all except a few. I can do :

out = subprocess.check_output(['['find', '.', '-maxdepth', '1', '!', '-iname', 'a', '!' '-iname', 'b', '!' '-iname', 'c', '!' , '-iname', 'd', '-exec',  'rm', '-rf',  '{}' , '+'])

But I want to specify all not to delete dirs and files in a list instead of making the command so long, and tough to read, ie, something like:

goodfilesList = ['a', 'b','c', 'd']
out = subprocess.check_output(['find', '.', '-maxdepth', '1', '!', '-iname'] + goodfilesList)
yogkm
  • 649
  • 5
  • 15
Shayan Anwar
  • 149
  • 2
  • 10
  • 1
    you can try `set([1,2,6,8]) - set([2,3,5,8])`. This gives `set([1, 6])` https://stackoverflow.com/a/4211239/2861108 – MjZac Feb 18 '19 at 07:23

1 Answers1

0

You can try list compression to create the command you want.

something like:

flist = ['a','b','c']

command = ['find', '.', '-maxdepth', '1']
[command.extend(['!','-iname',fname]) for fname in flist] # command ==  ['find', '.', '-maxdepth', '1', '!', '-iname', 'a', '!', '-iname', 'b', '!', '-iname', 'c']
command.extend(['-exec',  'rm', '-rf',  '{}' , '+'])

out = subprocess.check_output(command)
Michael Bridges
  • 351
  • 2
  • 6