Created
August 15, 2015 10:26
-
-
Save marshyon/3a107a628762a47a9ae9 to your computer and use it in GitHub Desktop.
Simple Go program to read a file line by line, strip null characters using a regular expression and write the output to an output file
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 ( | |
"bufio" | |
"flag" | |
"fmt" | |
"os" | |
"regexp" | |
) | |
func check(e error) { | |
if e != nil { | |
fmt.Printf("Failed to open file => %s\n", e) | |
panic(e) | |
} | |
} | |
/* | |
* | |
* USAGE : | |
* go run stripNulls.go --inputFile out.txt --outputFile safe.txt | |
* | |
*/ | |
func main() { | |
// command line arguments | |
inputFilePtr := flag.String("inputFile", "foo", "input filename") | |
outputFilePtr := flag.String("outputFile", "bar", "output filename") | |
flag.Parse() | |
fmt.Println("inputFile:", *inputFilePtr) | |
// compile regex | |
reg, err := regexp.Compile("\\x00") | |
check(err) | |
// open file for reading | |
file, err := os.Open(*inputFilePtr) | |
check(err) | |
defer file.Close() | |
// open output file | |
outputF, err := os.Create(*outputFilePtr) | |
check(err) | |
defer outputF.Close() | |
// read file line by line and strip null characters | |
scanner := bufio.NewScanner(file) | |
for scanner.Scan() { | |
myStr := scanner.Text() | |
safe := reg.ReplaceAllString(myStr, "") | |
safeStr := fmt.Sprint(safe, "\n") | |
n3, err := outputF.WriteString(safeStr) | |
check(err) | |
fmt.Printf("wrote %d bytes\n", n3) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment