Reputation: 2747
I am trying to search for or a particular words in the files in a directory and and convert each of its instance in all the file in Uppercase.
I want to keep track of the file where the word was found and how many time it appeared in those file.
So far I am able to read the content of the file.
How do send an argument then from the main function to search through the file and replace those instance into upper case?
This is what I have so far:
func visit(path string, fi os.FileInfo, err error) error {
if err!=nil{
return err
}
if !!fi.IsDir(){
return nil //
}
matched, err := filepath.Match("*.txt", fi.Name())
if err !=nil{
fmt.Println(err)
return err
}
if matched{
read,err:= ioutil.ReadFile(path)
fmt.Println(read)
check(err)
fmt.Println(path) }
return nil
}
func main() {
err := filepath.Walk(".", visit)
}
Upvotes: 2
Views: 2201
Reputation: 1323743
You can use a variable which is seen by a callback
function literal, used by filepath.Walk
, as a closure.
See for instance "GOLANG: Walk Directory Tree and Process Files".
func main() {
var yourWord := "a word"
callback := func(path string, fi os.FileInfo, err error) error {
// do something with yourWord!
}
filepath.Walk(".", callback)
}
That means:
visit
(which cannot be called with any additional parameters, like yourWord
)callback
function (function literal) just before calling filepath.Walk
with itAnonymous functions can be declared in Go.
Function literals are closures: they inherit the scope of the function in which they are declared.
They may refer to variables defined in a surrounding function. Those variables are then shared between the surrounding function and the function literal, and they survive as long as they are accessible.
In your case, the 'callback' function literal will inherit from the variable yourWord
defined before.
Note: the function to call is strings.ToUpper()
, not strings.toUpper()
.
Upvotes: 1