Golang : Delete certain files in a directory
Encounter a situation today where I need to delete some files in a directory. Not all files, but some files with certain pattern in their names. This code below will demonstrate how to scan a given directory and delete those unwanted files.
Let say I want to remove all files that have "dumb_" in their names and not others.
ls -la testdir/
total 0
drwxr-xr-x 5 sweetlogic staff 170 Oct 24 10:07 .
drwxr-xr-x+ 45 sweetlogic staff 1530 Oct 24 10:06 ..
-rw-r--r-- 1 sweetlogic staff 0 Oct 23 15:13 dumb3.txt
-rw-r--r-- 1 sweetlogic staff 0 Oct 23 15:13 dumb_1.txt
-rw-r--r-- 1 sweetlogic staff 0 Oct 23 15:13 dumb_2.txt
and the program code :
scandelete.go
package main
import (
"flag"
"os"
"path/filepath"
"strings"
)
var flagPath = flag.String("path", "", "path to walk in search for dumb_* files to delete.")
func deletefiles(path string, f os.FileInfo, err error) (e error) {
// check each file if starts with the word "dumb_"
if strings.HasPrefix(f.Name(), "dumb_") {
os.Remove(path)
}
return
// See https://www.socketloop.com/tutorials/golang-delete-files-by-extension
// on how to delete file by extension
}
func init() {
flag.Parse()
}
func main() {
// check if the user specify a path
if *flagPath == "" {
flag.Usage() // if no, prompt usage
os.Exit(0) // and exit
}
// walk through the files in the given path and perform partialrename()
// function
filepath.Walk(*flagPath, deletefiles)
}
result after executing this command ./scandelete -path="/Users/sweetlogic/testdir"
ls -la
total 0
drwxr-xr-x 3 sweetlogic staff 102 Oct 24 10:08 .
drwxr-xr-x+ 46 sweetlogic staff 1564 Oct 24 10:07 ..
-rw-r--r-- 1 sweetlogic staff 0 Oct 23 15:13 dumb3.txt
May you find this simple tutorial useful :-)
By Adam Ng
IF you gain some knowledge or the information here solved your programming problem. Please consider donating to the less fortunate or some charities that you like. Apart from donation, planting trees, volunteering or reducing your carbon footprint will be great too.
Advertisement
Tutorials
+11.7k Golang : convert(cast) float to string
+5.2k Python : Convert(cast) string to bytes example
+8.7k Golang : On lambda, anonymous, inline functions and function literals
+5k Golang : Check if a word is countable or not
+7k Javascript : How to get JSON data from another website with JQuery or Ajax ?
+7.3k Golang : How to detect if a sentence ends with a punctuation?
+14.6k Golang : Find commonalities in two slices or arrays example
+20.1k Golang : Check if os.Stdin input data is piped or from terminal
+4.5k Linux : sudo yum updates not working
+18.3k Golang : How to get hour, minute, second from time?
+5.3k Golang : Reclaim memory occupied by make() example
+8.7k Golang : Executing and evaluating nested loop in html template