How do I issue a command under bashro delete all files in current directory with 2-character names?

I've done every possible combinations I can think of:

rm -r ?? . rm -r [??]. rm -r ??. 

I'm not list the other ones I've come up with but I'm out of ideas here.

2

2 Answers

I asked in a comment above if this was to remove two-character length filenames in the current directory or in the current directory AND subdirectories. I'll list both solutions here:

To delete files that have a 2-character length filename in the current directory

rm ?? 

To delete files that have a 2-character length filename in the current directory as well as subdirectories:

find . -name '??' -exec rm -rf {} \; 

This one is a bit trickier since the filenames take on the path as you traverse through subdirectories. Instead of trying to figure this out with the rm command, we use find by name with the ?? for the 2 character wildcard and then use the -exec option to do the rm on whatever is found {}.

3

Use find with exec. First do a dry run like this to make sure you are not acting on things you don’t want to act on:

find . -maxdepth 1 -type f -name '??' -exec ls -latr {} \; 

Then when you are positive it works the way you wish, run this:

find . -maxdepth 1 -type f -name '??' -exec rm -rf {} \; 

Also, pay attention to maxdepth. That will contain your actions to just the current directory. Without maxdepth the find command will run rampant all over your system just doing whatever to two character filenames. Of course increase maxdepth to match whatever depth you want to go to, but remember that you run the risk of damaging your system if you do not use that and do some dry run tests on the find logic before running the rm -rf.

With GNU find (which is in most of Linux distributions) you can also use the option -delete instead of -exec rm -rf {} \;. -delete could be slightly more effective because it does not need to call an external command but it is not part of the POSIX specification.

1

Your Answer

Sign up or log in

Sign up using Google Sign up using Facebook Sign up using Email and Password

Post as a guest

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