forked from aws-samples/aws-lambda-extensions
-
Notifications
You must be signed in to change notification settings - Fork 0
/
files_with_substring.go
49 lines (43 loc) · 1.08 KB
/
files_with_substring.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
// SPDX-License-Identifier: MIT-0
package main
import (
"fmt"
"os"
"path/filepath"
"strings"
)
func renameFilesWithSubstring(rootDirectory string, substring string, newName string) (int, error) {
files, err := getFilesWithSubstring(rootDirectory, substring)
if err != nil {
return 0, err
}
for idx, file := range files {
if idx == 0 {
err = os.Rename(file, fmt.Sprintf("%s/%s", filepath.Dir(file), newName))
if err != nil {
return idx, err
}
} else {
err = os.Rename(file, fmt.Sprintf("%s/%s(%d)", filepath.Dir(file), newName, idx))
if err != nil {
return idx, err
}
}
}
return len(files), nil
}
func getFilesWithSubstring(rootDirectory string, substring string) ([]string, error) {
var files []string
err := filepath.Walk(rootDirectory, func(path string, info os.FileInfo, err error) error {
substringFound := strings.Contains(path, substring)
if substringFound {
files = append(files, path)
}
return nil
})
if err != nil {
return nil, err
}
return files, nil
}