How can I search for .bak files in both the current directory and subdirectories at once?

0
13
Asked By CuriousCoder92 On

I'm trying to write a script that grabs a specific file type, specifically .bak files, from both the current directory and any subdirectories. I've managed to make it work separately: one script for the current directory using `for f in *.bak`, and another for subdirectories with `for f in ./**/*.bak`. However, I want to combine these commands so that I can find .bak files in one go instead of running two separate commands. Is there a way to do this in a single line?

2 Answers

Answered By TechWhiz123 On

You can combine your search using the `find` command. Try using: `for f in $(find . -iname '*.bak')`. This will search all directories starting from the current one and should give you all the .bak files in one go! If you need to execute a command on each of those files, you might also consider using something like `find . -iname '*.bak' -exec yourCommandHere '{}' ;`. That should help streamline your script!

HelpfulUser456 -

Just a heads up, I've tried the `for f` method and it works well, but sometimes it can crash if the script tries to load files into other programs from subdirectories. It might be worth debugging why that's happening for you.

Answered By ScriptGuru88 On

Another approach could be sticking with your original loop but using a wildcard for the directories: `for f in **/*.bak`, provided your shell supports it. This way, you wouldn't need to implement `find` at all and can keep it simpler!

Related Questions

LEAVE A REPLY

Please enter your comment!
Please enter your name here

This site uses Akismet to reduce spam. Learn how your comment data is processed.