Delete all files with the same name but different extensions

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
	}
}

This code could helps you.

package main

import (
	"fmt"
	"io/ioutil"
	"log"
	"os"
	"strings"
)

func main() {
	file, err := os.Create("1.txt")
	if err != nil {
		log.Fatal(err)
	}
	file.Close()

	var name string
	fmt.Println("File name")
	fmt.Scanf("%s\n", &name)

	path := "./"
	files, err := ioutil.ReadDir(path)
	if err != nil {
		log.Fatal(err)
	}

	for _, file := range files {
		filename := file.Name()
		if !file.IsDir() && strings.HasPrefix(filename, name) {
			fmt.Println("Removing ", filename)
			if err := os.Remove(filename); err != nil {
				log.Fatal(err)
			}
		}
	}
}

1 Like

Thank you. This really helped

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
    }
3 Likes

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.