Skip to content

Instantly share code, notes, and snippets.

@jumoog
Last active August 1, 2024 22:59
Show Gist options
  • Save jumoog/668b001017a388dd81ddbd9e9b4b2753 to your computer and use it in GitHub Desktop.
Save jumoog/668b001017a388dd81ddbd9e9b4b2753 to your computer and use it in GitHub Desktop.
rename all files in folder; split "_" the filename and remove the last part
// go build rename_files.go
package main
import (
"fmt"
"os"
"path/filepath"
"strings"
)
func main() {
// Check if the directory path is provided as an argument
if len(os.Args) < 2 {
fmt.Println("Usage: go run rename_files.go <directory-path>")
return
}
// Get the directory path from the command-line argument
dir := os.Args[1]
// Open the directory
files, err := os.ReadDir(dir)
if err != nil {
fmt.Println("Error reading directory:", err)
return
}
// Iterate over the files in the directory
for _, file := range files {
if file.IsDir() {
continue // Skip directories
}
oldName := file.Name()
ext := filepath.Ext(oldName) // Get the file extension
base := strings.TrimSuffix(oldName, ext) // Get the base name without the extension
parts := strings.Split(base, "_") // Split the base name by "_"
if len(parts) > 1 {
newBase := strings.Join(parts[:len(parts)-1], "_") // Join all parts except the last one
newName := newBase + ext // Construct the new file name with the extension
oldPath := filepath.Join(dir, oldName)
newPath := filepath.Join(dir, newName)
// Rename the file
err := os.Rename(oldPath, newPath)
if err != nil {
fmt.Println("Error renaming file:", err)
} else {
fmt.Printf("Renamed: %s -> %s\n", oldName, newName)
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment