Last active
August 29, 2015 14:01
-
-
Save ShawnMilo/6f2d03f8e87db760d127 to your computer and use it in GitHub Desktop.
A Go program for replacing spaces in filenames with underscores.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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