Skip to content

Instantly share code, notes, and snippets.

@ShawnMilo
Last active August 29, 2015 14:01
Show Gist options
  • Save ShawnMilo/6f2d03f8e87db760d127 to your computer and use it in GitHub Desktop.
Save ShawnMilo/6f2d03f8e87db760d127 to your computer and use it in GitHub Desktop.
A Go program for replacing spaces in filenames with underscores.
package main
// Using filenames or filename patters (using glob symbols), find filenames
// with spaces in the names and replace the spaces with underscores.
import (
"log"
"os"
"path"
"path/filepath"
"strings"
)
func main() {
args := os.Args[1:]
if len(args) == 0 {
log.Fatalf("No files passed.\n")
}
for _, arg := range args {
files, err := filepath.Glob(arg)
if err != nil {
log.Fatal(err)
}
if len(files) == 0 {
log.Printf("No files found matching %s.\n", arg)
continue
}
for _, file := range files {
base := path.Base(file)
if strings.Index(base, " ") == -1 {
continue
}
new := path.Join(path.Dir(file), strings.Replace(base, " ", "_", -1))
_, err := os.Stat(new)
if err == nil {
log.Printf("Not renaming %s; %s already exists.\n", file, new)
continue
}
err = os.Rename(file, new)
if err != nil {
log.Fatal(err)
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment