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
+23.9k Golang : How to validate URL the right way
+13.1k Golang : Count number of runes in string
+9.4k Golang : Find correlation coefficient example
+12.3k Golang : Exit, terminating or aborting a program
+9.5k Golang : ffmpeg with os/exec.Command() returns non-zero status
+36.1k Golang : Convert date or time stamp from string to time.Time type
+7.8k Golang : Get all countries phone codes
+5.7k Golang : Detect variable or constant type
+17.7k Golang : Convert IPv4 address to decimal number(base 10) or integer
+6.3k Elasticsearch : Shutdown a local node
+5.1k Unix/Linux/MacOSx : How to remove an environment variable ?
+5.6k Golang : Find change in a combination of coins example