Golang : Rename part of filename
This simple tutorial is a code fragment extract from previous tutorial for scanning and renaming partial filenames showing how you can rename part of a filename in Go.
var f os.FileInfo
path := `\targetfile.txt`
// check each file if starts with the word "dumb_"
// depending on your needs
// you can replace HasPrefix with http://golang.org/pkg/strings/#Contains or http://golang.org/pkg/strings/#HasSuffix
if strings.HasPrefix(f.Name(), "dumb_") {
base := filepath.Base(path) // get the file's basename
dir := filepath.Dir(path)
renameto := filepath.Join(dir, strings.Replace(base, "dumb_", "smart_", 1))
os.Rename(path, renameto)
}
See full example at https://www.socketloop.com/tutorials/golang-scan-files-for-certain-pattern-and-rename-part-of-the-files
See also : Golang : Scan files for certain pattern and rename part of the files
By Adam Ng
IF you gain some knowledge or the information here solved your programming problem. Please consider donating to the less fortunate or some charities that you like. Apart from donation, planting trees, volunteering or reducing your carbon footprint will be great too.
Advertisement
Tutorials
+21.4k Golang : simulate tail -f or read last line from log file example
+14.7k Golang : Read a file line by line
+5.6k Golang : Totalize or add-up an array or slice example
+19.1k Golang : How to force compile or remove object files first before rebuild?
+8.3k Golang : Find correlation coefficient example
+5.5k Golang : Combine slices of complex numbers and operation example
+6.1k Javascript : How to get JSON data from another website with JQuery or Ajax ?
+17.2k Golang : Generate thumbnails from images
+8.3k Golang : Qt Yes No and Quit message box example
+16.1k Golang : How to make a file read only and set it to writable again?
+5.2k Linux/Unix : Commands that you need to be careful about