Go implements a Find directory (including subdirectories) to replace the contents of a file

Source: Internet
Author: User
This is a creation in Article, where the information may have evolved or changed.

function

Finds the file by the specified directory, and if there is a subdirectory, the subdirectory will also search for the contents of the file to be replaced.

Defects

1. No text file is filtered out

2. When the file is too large, the efficiency is not high

Code

Package Mainimport ("Flag" "FMT" "Io/ioutil" "OS" "Path/filepath" "strings") type Replacehelper struct {Root    string// root directory OldText string//text to be replaced NewText string//New text}func (H *replacehelper) Dowrok () error {return filepath. Walk (H.root, H.walkcallback)}func (H replacehelper) walkcallback (path string, F OS. FileInfo, err Error) error {if Err! = Nil {return err}if f = = nil {return nil}if F.isdir () {//fmt. Pringln ("DIR:", path) return nil}//file type needs to be filtered buf, err: = Ioutil. ReadFile (PATH) if err! = Nil {//errreturn err}content: = String (BUF)//replace newcontent: = Strings. Replace (content, H.oldtext, H.newtext,-1)//re-write Ioutil. WriteFile (Path, []byte (Newcontent), 0) return Err}func main () {flag. Parse () Helper: = Replacehelper{root:    flag. ARG (0), Oldtext:flag. ARG (1), Newtext:flag. ARG (2),}err: = helper. Dowrok () If Err = = Nil {fmt. Println ("done!")} else {fmt. Println ("Error:", err.) Error ())}}

  

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.