Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

BASH: How to remove all files except those named in a manifest?

I have a manifest file which is just a list of newline separated filenames. How can I remove all files that are not named in the manifest from a folder?

I've tried to build a find ./ ! -name "filename" command dynamically:

command="find ./ ! -name \"MANIFEST\" "
for line in `cat MANIFEST`; do
    command=${command}"! -name \"${line}\" " 
done
command=${command} -exec echo {} \;
$command

But the files remain.

[Note:] I know this uses echo. I want to check what my command does before using it.

Solution:(thanks PixelBeat)

ls -1 > ALLFILES
sort MANIFEST MANIFEST ALLFILES | uniq -u | xargs rm

Without temp file:

ls -1 | sort MANIFEST MANIFEST - | uniq -u | xargs rm

Both Ignores whether the files are sorted/not.

like image 289
brice Avatar asked May 06 '10 16:05

brice


People also ask

How do I delete all files except a specific file extension?

Highlight all the files you want to keep by clicking the first file type, hold down the Shift key, and click the last file. Once all the files you want to keep are highlighted, on the Home Tab, click Invert Selection to select all other files and folders.

How do you delete all files except the latest three in a folder windows?

You can just use the -u switch on sort to get rid of duplicates. You don't need this part anyway. tail -n +4 is printing all lines in the output of ls -t1 starting with the fourth line (i.e. the three most recently modified files won't be listed) xargs rm -r says to delete any file output from the tail .


2 Answers

For each file in current directory grep filename in MANIFEST file and rm file if not matched.

for file in *
  do grep -q -F "$file" PATH_TO_YOUR_MANIFIST ||  rm "$file" 
done
like image 76
Jürgen Hötzel Avatar answered Oct 24 '22 00:10

Jürgen Hötzel


Using the "set difference" pattern from http://www.pixelbeat.org/cmdline.html#sets

(find ./ -type f -printf "%P\n"; cat MANIFEST MANIFEST; echo MANIFEST) |
  sort | uniq -u | xargs -r rm

Note I list MANIFEST twice in case there are files listed there that are not actually present. Also note the above supports files in subdirectories

like image 36
pixelbeat Avatar answered Oct 24 '22 00:10

pixelbeat