Golang : Pad file extension automagically
Problem:
You want to pad file type extension to a given filename string without prompting your program users to do so. Your program accepts extension of certain type only. How to pad the missing file type extension automatically?
Solution:
Use strings.HasSuffix()
function to detect if the filename string has the file type extension. If not, pad the filename string with the file extension type.
Here you go!
package main
import (
"strings"
"os"
"fmt"
)
func main() {
if len(os.Args) != 2 {
fmt.Printf("Usage : %s <filename.ext>\n", os.Args[0])
os.Exit(0)
}
inputFileName := os.Args[1]
fmt.Println("Input file name is : ", inputFileName)
if !strings.HasSuffix(inputFileName, ".ext") { // check if the .ext is in the string
fmt.Println("Input file name does not have extension. Padding now")
inputFileName += ".ext"
fmt.Println("Input file name with extension padded : ", inputFileName)
} else {
fmt.Println("Input file name already has extension : ", inputFileName)
}
}
Sample outputs:
./padfileextent testfilenamewithoutextension.bmp
Input file name is : testfilenamewithoutextension.bmp
Input file name does not have extension. Padding now
Input file name with extension padded : testfilenamewithoutextension.bmp.ext
NOTE : Still pad with .ext because the filename does not have the required extension
./padfileextent testfilenamewithoutextension
Input file name is : testfilenamewithoutextension
Input file name does not have extension. Padding now
Input file name with extension padded : testfilenamewithoutextension.ext
./padfileextent testfilenamewithoutextension.ext
Input file name is : testfilenamewithoutextension.ext
Input file name already has extension : testfilenamewithoutextension.ext
References:
https://www.socketloop.com/tutorials/golang-get-command-line-arguments
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
+6.6k Golang : Get expvar(export variables) to work with multiplexer
+30.1k Golang : How to redirect to new page with net/http?
+14.2k Golang : How to check if your program is running in a terminal
+8.4k Golang : Set or add headers for many or different handlers
+27.2k Golang : Convert integer to binary, octal, hexadecimal and back to integer
+4.5k Golang : How to pass data between controllers with JSON Web Token
+10.3k Golang : ISO8601 Duration Parser example
+10.9k Golang : Intercept and process UNIX signals example
+26.5k Golang : Force your program to run with root permissions
+6.9k Golang : Transform lisp or spinal case to Pascal case example
+17.2k Golang : Clone with pointer and modify value
+27.1k Golang : dial tcp: too many colons in address