Last active
December 26, 2017 13:10
-
-
Save jiro4989/8116922368a04415f0f0893edd591f92 to your computer and use it in GitHub Desktop.
ファイル名に含まれる数字を0埋めしてリネームするスクリプト(powershell, python, go)
This file contains 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 | |
import ( | |
"fmt" | |
"io/ioutil" | |
"log" | |
"os" | |
"path/filepath" | |
"regexp" | |
) | |
func init() { | |
log.SetFlags(log.Ldate | log.Ltime | log.Lshortfile) | |
} | |
func main() { | |
dirName := "dummy" | |
// ディレクトリ配下のすべてのファイルの取得 | |
files, err := ioutil.ReadDir(dirName) | |
if err != nil { | |
log.Fatal(err) | |
} | |
re := regexp.MustCompile(`(\d+)`) | |
for _, f := range files { | |
// 取得したファイルのパスの取得 | |
fn := f.Name() | |
fp := filepath.Join(dirName, fn) | |
// ファイルの番号の取得 | |
m := re.FindString(fn) | |
// 0埋めしたファイル名を取得 | |
nfn := fmt.Sprintf("dummy%03s.zip", m) | |
// 0埋めファイルパスの取得 | |
nfp := filepath.Join(dirName, nfn) | |
// ファイルのリネーム | |
err := os.Rename(fp, nfp) | |
if err != nil { | |
log.Fatal(err) | |
} | |
fmt.Println(fp, " >> ", nfp) | |
} | |
} |
This file contains 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
$dir = "dummy" | |
$reg = [regex]"(\d+)" | |
ls $dir | % { | |
$name = $_.Name | |
$num = $reg.Matches($name)[0].Value | |
$padnum = $num.PadLeft(3, "0") | |
mv "$dir\$name" "$dir\dummy$padnum.zip" | |
} | |
ls "dummy" |
This file contains 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
#!/usr/bin/env python3 | |
# -*- coding: utf-8 -*- | |
import os, re | |
def main(): | |
for f in os.listdir("dummy"): | |
num = re.search(r"(\d+)", f).group(1) | |
of = "dummy/" + f | |
nf = "dummy/dummy{0:03d}.zip".format(int(num)) | |
try: | |
os.rename(of, nf) | |
print(of, " >> ", nf) | |
except: | |
print(u"リネーム前と後が同じです。", nf) | |
if __name__ == '__main__': | |
main() | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment