Skip to content

Instantly share code, notes, and snippets.

@rominirani
Created July 17, 2015 11:05
Show Gist options
  • Save rominirani/b6375585242c390c60e8 to your computer and use it in GitHub Desktop.
Save rominirani/b6375585242c390c60e8 to your computer and use it in GitHub Desktop.
Go Course : Exercise 17
/*
Manipulate a text file.Search for 'word' in this text file and replace it with 'inserted word'. Write the contents
back into the original file
*/
package main
import (
"bytes"
"fmt"
"io/ioutil"
"log"
"os"
)
func check(e error) {
if e != nil {
log.Fatal(e)
}
}
func main() {
//Check for program arguments
args := os.Args
numArgs := len(args)
if numArgs != 2 {
log.Fatal("You must provide the text file name")
}
filename := args[1]
file, err := ioutil.ReadFile(filename)
check(err)
output := bytes.Replace(file, []byte("word"), []byte("inserted word"), -1)
err = ioutil.WriteFile(filename, output, 0666)
check(err)
fmt.Println("File has been modified successfully.")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment