Hello. I need help. It is necessary to write a program that deletes all files with the same name and different extensions (for example, we specify the name “1” in the terminal, and all files with the name “1” (1.txt, 1.docx, 1.xlsx, etc.) are deleted ).
Here’s what I was able to do
package main
import (
"fmt"
"log"
"os"
)
func main() {
file, erPreformatted textr := os.Create("1.txt")
if err != nil {
log.Fatal(err)
}
file.Close()
var name string
fmt.Println("File name")
fmt.Scanf("%s\n", &name)
err = os.Remove(name)
if err != nil {
fmt.Println(err)
return
}
}
Beware that this will delete every file that starts with “1” including “1st draft.docx”, etc… I would instead recommend flipping this around and instead of matching a prefix, try removing the extension and match against the rest of the entire filename.
for _, file := range files {
filename := file.Name()
ext := filepath.Ext(filename)
prefix := filename[:len(filename)-len(ext)]
if prefix == name {
// remove it
}