On Sat, 22 Apr 2017 08:08:57 -0700 (PDT) Vikas Kumar <vikas...@gmail.com> wrote:
> I am trying to iterate over an array, match the lines in a file and > then delete all occurrences of the lines in the file. > > See this example. > *Array* > var abcd = [5]string{ > "one two", > "three four fix", > "six", > "seven eight nine ten", > "eleven twelve thirteen fourteen fifteen", > } You don't have to explicitly spell the length here -- should you have used "..." instead, the compiler would have calculated the length itself. An even better approach in this particular case would be to use a slice rather than an array: var abcd = []string{"blah", ...} > *My File* > <some text> - one two > <some text> - seven eight nine ten > <some text> - one two > <some text> - nineteen > <some text> - eleven twelve thirteen fourteen fifteen > <some text> - sixteen seventeen eighteen > > *Desired File* > <some text> - nineteen > <some text> - sixteen seventeen eighteen > > In Bash, I would have done something like this. > for i in "${abcd[@]}" > do > sed -i "/$i/d" <my_file> > done Well, sed really does not do anything super-special: it reads the file line-by-line and produces *another* file with the updated information. After reading of the source file is over -- and hence producing of the output file is over, too, -- sed would rename the new file over the old one. So you should do the same: 1. Use the functions from the path/filepath package to obtain the name of the directory the source file is located in. 2. Use the io/ioutil.TempFile() to obtain a temporary file beside the source one -- that is, in the same directory. 3. Use the bufio.Scanner type to read the source file in a linewise manner. 4. Use the functions from the "strings" stdlib package to deal with each line read from the source file. If the line read matches one of your patterns, you simply move on to reading the next line; otherwise you write in to the output file. 5. Once the input is exhausted, Flush() and Close() the output file and then use os.Rename() to rename the output file *over* the source file. Be sure to check all error values returned from all the functions you call. Note that you'd better to actually start with a good book on Go -- I'd personally recommend to start with the "Effective Go" online paper and then move on to "The Go Programming Language" by Donovan and Kernigan; if you have almost no experience with compiled or C-like languages you might consider reading first the book by Caleb Doxsey available freely as a PDF document. -- You received this message because you are subscribed to the Google Groups "golang-nuts" group. To unsubscribe from this group and stop receiving emails from it, send an email to golang-nuts+unsubscr...@googlegroups.com. For more options, visit https://groups.google.com/d/optout.