14

I am trying to delete files with a wildcard like shell scripts like:

c:\del 123_*

My trial as below was failed.

os.RemoveAll("/foo/123_*") os.Remove("/foo/123_*") 

I guess I need to use some library to use a wildcard.
What is good practice for deleting files with a wildcard?

3
  • 1
    Read the directory, select the files wich match the desired pattern and Remove them. No library but some programming. Commented Jan 3, 2018 at 6:29
  • 2
    Or something with filepath.Glob. Commented Jan 3, 2018 at 6:44
  • 1
    The wildcard * is a feature of the shell, not one of the file system. So you have to go through the list of files and test their names against a pattern. The regexp package can deal with complicated patterns, however strings.HasPrefix(str, prefix) can do the task at hand quite well. Commented Jan 3, 2018 at 7:26

1 Answer 1

37

As people mentioned wildcard is a feature of shell (e.g. Windows cmd.exe) not OS and usually programming languages don't provide equivalent of del xyz*. You should use Glob function to find files you want to delete.

files, err := filepath.Glob("/foo/123_*") if err != nil { panic(err) } for _, f := range files { if err := os.Remove(f); err != nil { panic(err) } } 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.