package cmd import ( "fmt" "os" "strings" "github.com/spf13/cobra" ) // renameCmd represents the rename command var renameCmd = &cobra.Command{ Use: "rename", Short: "Rename files in bulk based on specified patterns", Long: `Rename files in bulk based on specified patterns. Example usage: dttt rename --pattern "prefix_###.jpg" --start 1 --directory ./images`, Run: func(cmd *cobra.Command, args []string) { // Handle command logic here directory, _ := cmd.Flags().GetString("directory") pattern, _ := cmd.Flags().GetString("pattern") start, _ := cmd.Flags().GetInt("start") // Check if required flags are provided if directory == "" || pattern == "" { cmd.Help() return } // Implement the renaming logic renameFiles(directory, pattern, start) }, } func init() { rootCmd.AddCommand(renameCmd) // Define flags and configuration settings for the command renameCmd.Flags().StringP("directory", "d", ".", "Directory containing the files to rename") renameCmd.Flags().StringP("pattern", "p", "", "Pattern for renaming files. Use '###' as a placeholder for numeric sequence.") renameCmd.Flags().IntP("start", "s", 1, "Start index for numeric sequence in the renaming pattern") } // Function to rename files in bulk based on the specified pattern func renameFiles(directory, pattern string, start int) { // List files in the specified directory files, err := os.ReadDir(directory) if err != nil { fmt.Println("Error:", err) return } // Iterate through each file in the directory for i, file := range files { // Generate the new filename based on the pattern newName := strings.Replace(pattern, "###", fmt.Sprintf("%d", start+i), 1) // Rename the file err := os.Rename(file.Name(), newName) if err != nil { fmt.Println("Error renaming file:", err) continue } fmt.Printf("Renamed %s to %s\n", file.Name(), newName) } }