1

I have a list of files & directories in a file in some order, and I want to write a script that removes them.

Directories are only supposed to be removed if all of their descendents will also be removed.
(Put another way, they should only be removed if they'd be empty after the script has run many times.)

I'd really prefer to do this in 1 pass.
But doing this in 1 pass seems to require doing things in a correct order (post-order traversal).

I assume this is a known problem... how do people generally solve it in a shell script?

1

I assume this is a known problem... how do people generally solve it in a shell script?

They pass the list of files and directories to sort -r.

If you are getting the list of files and directories from find, you can also use the -depth option to ensure post-order traversal.

0

You could try ordering the files by the number of slashes in it ( descending ) , this way you should solve the ordering problem.

0

Never mind, I figured it out independently.

It can be done with awk. Note that this solution does not tolerate newlines in the file name.

awk -- '{a=$$0;b=$$0;print(gsub("/","/",a)-sub(/\/$$/,"aaa",b),$$0)}' INPUT_FILE.txt \
    |  "$(call Q2,/usr/bin/sort)" -k1,1nr \
    |  cut -d " " -f 2-

And while I'm here -- the lines can be de-duplicated through the following:

awk -- '{pos[$$0] = NR} END { for(key in pos) reverse[pos[key]] = key; for(nr=1;nr<=NR;nr++) if(nr in reverse) print reverse[nr] }' INPUT_FILE.txt

Note that de-duplication is critical to prevent exponential time blow-up if you end up recursing.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.