WeixiangYan/CodeTransOcean huggingface dataset:
Task: Input loop



C#: using System;
using System.IO;

class Program
{
    static void Main(string[] args)
    {
        
        

        using (var b = new StreamReader("file.txt"))
        {
            string line;
            while ((line = b.ReadLine()) != null)
                Console.WriteLine(line);
        }
    }
}




PHP: $fh = fopen($filename, 'r');
if ($fh) {
    while (!feof($fh)) {
        $line = rtrim(fgets($fh)); # removes trailing newline
        # process $line
    }
    fclose($fh);
}
Task: Input loop


C++: #include <istream>
#include <string>
#include <vector>
#include <algorithm>
#include <iostream>
#include <iterator>


template<class OutIt>
void read_words(std::istream& is, OutIt dest)
{
  std::string word;
  while (is >> word)
  {
    
    *dest = word;
  }
}


template<class OutIt>
void read_lines(std::istream& is, OutIt dest)
{
  std::string line;
  while (std::getline(is, line))
  {
    
    *dest = line;
  }
}

int main()
{
  
  read_words(std::cin, 
             std::ostream_iterator<std::string>(std::cout, " "));

  
  std::vector<std::string> v;
  read_lines(std::cin, std::back_inserter(v));
  
  return 0;
}





PHP: $fh = fopen($filename, 'r');
if ($fh) {
    while (!feof($fh)) {
        $line = rtrim(fgets($fh)); # removes trailing newline
        # process $line
    }
    fclose($fh);
}
Task: Input loop




Go: package main

import (
	"bufio"
	"io"
	"log"
	"os"
)

func main() {
	in := bufio.NewReader(os.Stdin)
	for {
		s, err := in.ReadString('\n')
		if err != nil {
			
			
			if err != io.EOF {
				log.Fatal(err)
			}
			break
		}
		
		
		_ = s
	}
}



PHP: $fh = fopen($filename, 'r');
if ($fh) {
    while (!feof($fh)) {
        $line = rtrim(fgets($fh)); # removes trailing newline
        # process $line
    }
    fclose($fh);
}
Task: Input loop





Java: import java.io.InputStream;
import java.util.Scanner;

public class InputLoop {
    public static void main(String args[]) {
        
        InputStream source = System.in;

        

        Scanner in = new Scanner(source);
        while(in.hasNext()){
            String input = in.next(); 

            
            System.out.println(input);
        }
    }
}


PHP: $fh = fopen($filename, 'r');
if ($fh) {
    while (!feof($fh)) {
        $line = rtrim(fgets($fh)); # removes trailing newline
        # process $line
    }
    fclose($fh);
}
Task: Input loop






PHP: $fh = fopen($filename, 'r');
if ($fh) {
    while (!feof($fh)) {
        $line = rtrim(fgets($fh)); # removes trailing newline
        # process $line
    }
    fclose($fh);
}


Python: while(True):
      x = input("What is your age? ")
      print(x)
Task: Input loop






PHP: $fh = fopen($filename, 'r');
if ($fh) {
    while (!feof($fh)) {
        $line = rtrim(fgets($fh)); # removes trailing newline
        # process $line
    }
    fclose($fh);
}



VB: Public Sub test()
    Dim filesystem As Object, stream As Object, line As String
    Set filesystem = CreateObject("Scripting.FileSystemObject")
    Set stream = filesystem.OpenTextFile("D:\test.txt")
    Do While stream.AtEndOfStream <> True
        line = stream.ReadLine
        Debug.Print line
    Loop
    stream.Close
End Sub
Task: Globally replace text in several files

C: #include <stdio.h>
#include <stdlib.h>
#include <stddef.h>
#include <string.h>
#include <sys/types.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <unistd.h>
#include <err.h>
#include <string.h>

char * find_match(const char *buf, const char * buf_end, const char *pat, size_t len)
{
	ptrdiff_t i;
	char *start = buf;
	while (start + len < buf_end) {
		for (i = 0; i < len; i++)
			if (start[i] != pat[i]) break;

		if (i == len) return (char *)start;
		start++;
	}
	return 0;
}

int replace(const char *from, const char *to, const char *fname)
{
#define bail(msg) { warn(msg" '%s'", fname); goto done; }
	struct stat st;
	int ret = 0;
	char *buf = 0, *start, *end;
	size_t len = strlen(from), nlen = strlen(to);
	int fd = open(fname, O_RDWR);

	if (fd == -1) bail("Can't open");
	if (fstat(fd, &st) == -1) bail("Can't stat");
	if (!(buf = malloc(st.st_size))) bail("Can't alloc");
	if (read(fd, buf, st.st_size) != st.st_size) bail("Bad read");

	start = buf;
	end = find_match(start, buf + st.st_size, from, len);
	if (!end) goto done; 

	ftruncate(fd, 0);
	lseek(fd, 0, 0);
	do {
		write(fd, start, end - start);	
		write(fd, to, nlen);		
		start = end + len;		
						
		end = find_match(start, buf + st.st_size, from, len);
	} while (end);

	
	if (start < buf + st.st_size)
		write(fd, start, buf + st.st_size - start);

done:
	if (fd != -1) close(fd);
	if (buf) free(buf);
	return ret;
}

int main()
{
	const char *from = "Goodbye, London!";
	const char *to   = "Hello, New York!";
	const char * files[] = { "test1.txt", "test2.txt", "test3.txt" };
	int i;

	for (i = 0; i < sizeof(files)/sizeof(char*); i++)
		replace(from, to, files[i]);

	return 0;
}



C#: using System.Collections.Generic;
using System.IO;

class Program {
    static void Main() {
        var files = new List<string> {
            "test1.txt",
            "test2.txt"
        };
        foreach (string file in files) {
            File.WriteAllText(file, File.ReadAllText(file).Replace("Goodbye London!", "Hello New York!"));
        }
    }
}
Task: Globally replace text in several files

C: #include <stdio.h>
#include <stdlib.h>
#include <stddef.h>
#include <string.h>
#include <sys/types.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <unistd.h>
#include <err.h>
#include <string.h>

char * find_match(const char *buf, const char * buf_end, const char *pat, size_t len)
{
	ptrdiff_t i;
	char *start = buf;
	while (start + len < buf_end) {
		for (i = 0; i < len; i++)
			if (start[i] != pat[i]) break;

		if (i == len) return (char *)start;
		start++;
	}
	return 0;
}

int replace(const char *from, const char *to, const char *fname)
{
#define bail(msg) { warn(msg" '%s'", fname); goto done; }
	struct stat st;
	int ret = 0;
	char *buf = 0, *start, *end;
	size_t len = strlen(from), nlen = strlen(to);
	int fd = open(fname, O_RDWR);

	if (fd == -1) bail("Can't open");
	if (fstat(fd, &st) == -1) bail("Can't stat");
	if (!(buf = malloc(st.st_size))) bail("Can't alloc");
	if (read(fd, buf, st.st_size) != st.st_size) bail("Bad read");

	start = buf;
	end = find_match(start, buf + st.st_size, from, len);
	if (!end) goto done; 

	ftruncate(fd, 0);
	lseek(fd, 0, 0);
	do {
		write(fd, start, end - start);	
		write(fd, to, nlen);		
		start = end + len;		
						
		end = find_match(start, buf + st.st_size, from, len);
	} while (end);

	
	if (start < buf + st.st_size)
		write(fd, start, buf + st.st_size - start);

done:
	if (fd != -1) close(fd);
	if (buf) free(buf);
	return ret;
}

int main()
{
	const char *from = "Goodbye, London!";
	const char *to   = "Hello, New York!";
	const char * files[] = { "test1.txt", "test2.txt", "test3.txt" };
	int i;

	for (i = 0; i < sizeof(files)/sizeof(char*); i++)
		replace(from, to, files[i]);

	return 0;
}


C++: #include <fstream>
#include <iterator>
#include <boost/regex.hpp>
#include <string>
#include <iostream>

int main( int argc , char *argv[ ] ) {
   boost::regex to_be_replaced( "Goodbye London\\s*!" ) ;
   std::string replacement( "Hello New York!" ) ;
   for ( int i = 1 ; i < argc ; i++ ) {
      std::ifstream infile ( argv[ i ] ) ;
      if ( infile ) {
	 std::string filetext( (std::istreambuf_iterator<char>( infile )) ,
	       std::istreambuf_iterator<char>( ) ) ;
	 std::string changed ( boost::regex_replace( filetext , to_be_replaced , replacement )) ;
	 infile.close( ) ;
	 std::ofstream outfile( argv[ i ] , std::ios_base::out | std::ios_base::trunc ) ;
	 if ( outfile.is_open( ) ) { 
	    outfile << changed ;
	    outfile.close( ) ;
	 }
      }
      else 
	 std::cout << "Can't find file " << argv[ i ] << " !\n" ;
   }
   return 0 ;
}
Task: Globally replace text in several files

C: #include <stdio.h>
#include <stdlib.h>
#include <stddef.h>
#include <string.h>
#include <sys/types.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <unistd.h>
#include <err.h>
#include <string.h>

char * find_match(const char *buf, const char * buf_end, const char *pat, size_t len)
{
	ptrdiff_t i;
	char *start = buf;
	while (start + len < buf_end) {
		for (i = 0; i < len; i++)
			if (start[i] != pat[i]) break;

		if (i == len) return (char *)start;
		start++;
	}
	return 0;
}

int replace(const char *from, const char *to, const char *fname)
{
#define bail(msg) { warn(msg" '%s'", fname); goto done; }
	struct stat st;
	int ret = 0;
	char *buf = 0, *start, *end;
	size_t len = strlen(from), nlen = strlen(to);
	int fd = open(fname, O_RDWR);

	if (fd == -1) bail("Can't open");
	if (fstat(fd, &st) == -1) bail("Can't stat");
	if (!(buf = malloc(st.st_size))) bail("Can't alloc");
	if (read(fd, buf, st.st_size) != st.st_size) bail("Bad read");

	start = buf;
	end = find_match(start, buf + st.st_size, from, len);
	if (!end) goto done; 

	ftruncate(fd, 0);
	lseek(fd, 0, 0);
	do {
		write(fd, start, end - start);	
		write(fd, to, nlen);		
		start = end + len;		
						
		end = find_match(start, buf + st.st_size, from, len);
	} while (end);

	
	if (start < buf + st.st_size)
		write(fd, start, buf + st.st_size - start);

done:
	if (fd != -1) close(fd);
	if (buf) free(buf);
	return ret;
}

int main()
{
	const char *from = "Goodbye, London!";
	const char *to   = "Hello, New York!";
	const char * files[] = { "test1.txt", "test2.txt", "test3.txt" };
	int i;

	for (i = 0; i < sizeof(files)/sizeof(char*); i++)
		replace(from, to, files[i]);

	return 0;
}




Go: package main

import (
    "bytes"
    "io/ioutil"
    "log"
    "os"
)

func main() {
    gRepNFiles("Goodbye London!", "Hello New York!", []string{
        "a.txt",
        "b.txt",
        "c.txt",
    })
}

func gRepNFiles(olds, news string, files []string) {
    oldb := []byte(olds)
    newb := []byte(news)
    for _, fn := range files {
        if err := gRepFile(oldb, newb, fn); err != nil {
            log.Println(err)
        }
    }
}

func gRepFile(oldb, newb []byte, fn string) (err error) {
    var f *os.File
    if f, err = os.OpenFile(fn, os.O_RDWR, 0); err != nil {
        return
    }
    defer func() {
        if cErr := f.Close(); err == nil {
            err = cErr
        }
    }()
    var b []byte
    if b, err = ioutil.ReadAll(f); err != nil {
        return
    }
    if bytes.Index(b, oldb) < 0 {
        return
    }
    r := bytes.Replace(b, oldb, newb, -1)
    if err = f.Truncate(0); err != nil {
        return
    }
    _, err = f.WriteAt(r, 0)
    return
}
Task: Globally replace text in several files

C: #include <stdio.h>
#include <stdlib.h>
#include <stddef.h>
#include <string.h>
#include <sys/types.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <unistd.h>
#include <err.h>
#include <string.h>

char * find_match(const char *buf, const char * buf_end, const char *pat, size_t len)
{
	ptrdiff_t i;
	char *start = buf;
	while (start + len < buf_end) {
		for (i = 0; i < len; i++)
			if (start[i] != pat[i]) break;

		if (i == len) return (char *)start;
		start++;
	}
	return 0;
}

int replace(const char *from, const char *to, const char *fname)
{
#define bail(msg) { warn(msg" '%s'", fname); goto done; }
	struct stat st;
	int ret = 0;
	char *buf = 0, *start, *end;
	size_t len = strlen(from), nlen = strlen(to);
	int fd = open(fname, O_RDWR);

	if (fd == -1) bail("Can't open");
	if (fstat(fd, &st) == -1) bail("Can't stat");
	if (!(buf = malloc(st.st_size))) bail("Can't alloc");
	if (read(fd, buf, st.st_size) != st.st_size) bail("Bad read");

	start = buf;
	end = find_match(start, buf + st.st_size, from, len);
	if (!end) goto done; 

	ftruncate(fd, 0);
	lseek(fd, 0, 0);
	do {
		write(fd, start, end - start);	
		write(fd, to, nlen);		
		start = end + len;		
						
		end = find_match(start, buf + st.st_size, from, len);
	} while (end);

	
	if (start < buf + st.st_size)
		write(fd, start, buf + st.st_size - start);

done:
	if (fd != -1) close(fd);
	if (buf) free(buf);
	return ret;
}

int main()
{
	const char *from = "Goodbye, London!";
	const char *to   = "Hello, New York!";
	const char * files[] = { "test1.txt", "test2.txt", "test3.txt" };
	int i;

	for (i = 0; i < sizeof(files)/sizeof(char*); i++)
		replace(from, to, files[i]);

	return 0;
}





Java: import java.io.*;
import java.nio.file.*;

public class GloballyReplaceText {

    public static void main(String[] args) throws IOException {

        for (String fn : new String[]{"test1.txt", "test2.txt"}) {
            String s = new String(Files.readAllBytes(Paths.get(fn)));
            s = s.replace("Goodbye London!", "Hello New York!");
            try (FileWriter fw = new FileWriter(fn)) {
                fw.write(s);
            }
        }
    }
}
Task: Globally replace text in several files

C: #include <stdio.h>
#include <stdlib.h>
#include <stddef.h>
#include <string.h>
#include <sys/types.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <unistd.h>
#include <err.h>
#include <string.h>

char * find_match(const char *buf, const char * buf_end, const char *pat, size_t len)
{
	ptrdiff_t i;
	char *start = buf;
	while (start + len < buf_end) {
		for (i = 0; i < len; i++)
			if (start[i] != pat[i]) break;

		if (i == len) return (char *)start;
		start++;
	}
	return 0;
}

int replace(const char *from, const char *to, const char *fname)
{
#define bail(msg) { warn(msg" '%s'", fname); goto done; }
	struct stat st;
	int ret = 0;
	char *buf = 0, *start, *end;
	size_t len = strlen(from), nlen = strlen(to);
	int fd = open(fname, O_RDWR);

	if (fd == -1) bail("Can't open");
	if (fstat(fd, &st) == -1) bail("Can't stat");
	if (!(buf = malloc(st.st_size))) bail("Can't alloc");
	if (read(fd, buf, st.st_size) != st.st_size) bail("Bad read");

	start = buf;
	end = find_match(start, buf + st.st_size, from, len);
	if (!end) goto done; 

	ftruncate(fd, 0);
	lseek(fd, 0, 0);
	do {
		write(fd, start, end - start);	
		write(fd, to, nlen);		
		start = end + len;		
						
		end = find_match(start, buf + st.st_size, from, len);
	} while (end);

	
	if (start < buf + st.st_size)
		write(fd, start, buf + st.st_size - start);

done:
	if (fd != -1) close(fd);
	if (buf) free(buf);
	return ret;
}

int main()
{
	const char *from = "Goodbye, London!";
	const char *to   = "Hello, New York!";
	const char * files[] = { "test1.txt", "test2.txt", "test3.txt" };
	int i;

	for (i = 0; i < sizeof(files)/sizeof(char*); i++)
		replace(from, to, files[i]);

	return 0;
}







Python: import fileinput

for line in fileinput.input(inplace=True):
    print(line.replace('Goodbye London!', 'Hello New York!'), end='')
Task: Globally replace text in several files


C++: #include <fstream>
#include <iterator>
#include <boost/regex.hpp>
#include <string>
#include <iostream>

int main( int argc , char *argv[ ] ) {
   boost::regex to_be_replaced( "Goodbye London\\s*!" ) ;
   std::string replacement( "Hello New York!" ) ;
   for ( int i = 1 ; i < argc ; i++ ) {
      std::ifstream infile ( argv[ i ] ) ;
      if ( infile ) {
	 std::string filetext( (std::istreambuf_iterator<char>( infile )) ,
	       std::istreambuf_iterator<char>( ) ) ;
	 std::string changed ( boost::regex_replace( filetext , to_be_replaced , replacement )) ;
	 infile.close( ) ;
	 std::ofstream outfile( argv[ i ] , std::ios_base::out | std::ios_base::trunc ) ;
	 if ( outfile.is_open( ) ) { 
	    outfile << changed ;
	    outfile.close( ) ;
	 }
      }
      else 
	 std::cout << "Can't find file " << argv[ i ] << " !\n" ;
   }
   return 0 ;
}


C#: using System.Collections.Generic;
using System.IO;

class Program {
    static void Main() {
        var files = new List<string> {
            "test1.txt",
            "test2.txt"
        };
        foreach (string file in files) {
            File.WriteAllText(file, File.ReadAllText(file).Replace("Goodbye London!", "Hello New York!"));
        }
    }
}
Task: Globally replace text in several files


C++: #include <fstream>
#include <iterator>
#include <boost/regex.hpp>
#include <string>
#include <iostream>

int main( int argc , char *argv[ ] ) {
   boost::regex to_be_replaced( "Goodbye London\\s*!" ) ;
   std::string replacement( "Hello New York!" ) ;
   for ( int i = 1 ; i < argc ; i++ ) {
      std::ifstream infile ( argv[ i ] ) ;
      if ( infile ) {
	 std::string filetext( (std::istreambuf_iterator<char>( infile )) ,
	       std::istreambuf_iterator<char>( ) ) ;
	 std::string changed ( boost::regex_replace( filetext , to_be_replaced , replacement )) ;
	 infile.close( ) ;
	 std::ofstream outfile( argv[ i ] , std::ios_base::out | std::ios_base::trunc ) ;
	 if ( outfile.is_open( ) ) { 
	    outfile << changed ;
	    outfile.close( ) ;
	 }
      }
      else 
	 std::cout << "Can't find file " << argv[ i ] << " !\n" ;
   }
   return 0 ;
}



Go: package main

import (
    "bytes"
    "io/ioutil"
    "log"
    "os"
)

func main() {
    gRepNFiles("Goodbye London!", "Hello New York!", []string{
        "a.txt",
        "b.txt",
        "c.txt",
    })
}

func gRepNFiles(olds, news string, files []string) {
    oldb := []byte(olds)
    newb := []byte(news)
    for _, fn := range files {
        if err := gRepFile(oldb, newb, fn); err != nil {
            log.Println(err)
        }
    }
}

func gRepFile(oldb, newb []byte, fn string) (err error) {
    var f *os.File
    if f, err = os.OpenFile(fn, os.O_RDWR, 0); err != nil {
        return
    }
    defer func() {
        if cErr := f.Close(); err == nil {
            err = cErr
        }
    }()
    var b []byte
    if b, err = ioutil.ReadAll(f); err != nil {
        return
    }
    if bytes.Index(b, oldb) < 0 {
        return
    }
    r := bytes.Replace(b, oldb, newb, -1)
    if err = f.Truncate(0); err != nil {
        return
    }
    _, err = f.WriteAt(r, 0)
    return
}
Task: Globally replace text in several files


C++: #include <fstream>
#include <iterator>
#include <boost/regex.hpp>
#include <string>
#include <iostream>

int main( int argc , char *argv[ ] ) {
   boost::regex to_be_replaced( "Goodbye London\\s*!" ) ;
   std::string replacement( "Hello New York!" ) ;
   for ( int i = 1 ; i < argc ; i++ ) {
      std::ifstream infile ( argv[ i ] ) ;
      if ( infile ) {
	 std::string filetext( (std::istreambuf_iterator<char>( infile )) ,
	       std::istreambuf_iterator<char>( ) ) ;
	 std::string changed ( boost::regex_replace( filetext , to_be_replaced , replacement )) ;
	 infile.close( ) ;
	 std::ofstream outfile( argv[ i ] , std::ios_base::out | std::ios_base::trunc ) ;
	 if ( outfile.is_open( ) ) { 
	    outfile << changed ;
	    outfile.close( ) ;
	 }
      }
      else 
	 std::cout << "Can't find file " << argv[ i ] << " !\n" ;
   }
   return 0 ;
}




Java: import java.io.*;
import java.nio.file.*;

public class GloballyReplaceText {

    public static void main(String[] args) throws IOException {

        for (String fn : new String[]{"test1.txt", "test2.txt"}) {
            String s = new String(Files.readAllBytes(Paths.get(fn)));
            s = s.replace("Goodbye London!", "Hello New York!");
            try (FileWriter fw = new FileWriter(fn)) {
                fw.write(s);
            }
        }
    }
}
Task: Globally replace text in several files



C#: using System.Collections.Generic;
using System.IO;

class Program {
    static void Main() {
        var files = new List<string> {
            "test1.txt",
            "test2.txt"
        };
        foreach (string file in files) {
            File.WriteAllText(file, File.ReadAllText(file).Replace("Goodbye London!", "Hello New York!"));
        }
    }
}


Go: package main

import (
    "bytes"
    "io/ioutil"
    "log"
    "os"
)

func main() {
    gRepNFiles("Goodbye London!", "Hello New York!", []string{
        "a.txt",
        "b.txt",
        "c.txt",
    })
}

func gRepNFiles(olds, news string, files []string) {
    oldb := []byte(olds)
    newb := []byte(news)
    for _, fn := range files {
        if err := gRepFile(oldb, newb, fn); err != nil {
            log.Println(err)
        }
    }
}

func gRepFile(oldb, newb []byte, fn string) (err error) {
    var f *os.File
    if f, err = os.OpenFile(fn, os.O_RDWR, 0); err != nil {
        return
    }
    defer func() {
        if cErr := f.Close(); err == nil {
            err = cErr
        }
    }()
    var b []byte
    if b, err = ioutil.ReadAll(f); err != nil {
        return
    }
    if bytes.Index(b, oldb) < 0 {
        return
    }
    r := bytes.Replace(b, oldb, newb, -1)
    if err = f.Truncate(0); err != nil {
        return
    }
    _, err = f.WriteAt(r, 0)
    return
}
Task: Globally replace text in several files



C#: using System.Collections.Generic;
using System.IO;

class Program {
    static void Main() {
        var files = new List<string> {
            "test1.txt",
            "test2.txt"
        };
        foreach (string file in files) {
            File.WriteAllText(file, File.ReadAllText(file).Replace("Goodbye London!", "Hello New York!"));
        }
    }
}



Java: import java.io.*;
import java.nio.file.*;

public class GloballyReplaceText {

    public static void main(String[] args) throws IOException {

        for (String fn : new String[]{"test1.txt", "test2.txt"}) {
            String s = new String(Files.readAllBytes(Paths.get(fn)));
            s = s.replace("Goodbye London!", "Hello New York!");
            try (FileWriter fw = new FileWriter(fn)) {
                fw.write(s);
            }
        }
    }
}
Task: Globally replace text in several files



C#: using System.Collections.Generic;
using System.IO;

class Program {
    static void Main() {
        var files = new List<string> {
            "test1.txt",
            "test2.txt"
        };
        foreach (string file in files) {
            File.WriteAllText(file, File.ReadAllText(file).Replace("Goodbye London!", "Hello New York!"));
        }
    }
}





Python: import fileinput

for line in fileinput.input(inplace=True):
    print(line.replace('Goodbye London!', 'Hello New York!'), end='')
Task: Globally replace text in several files





Java: import java.io.*;
import java.nio.file.*;

public class GloballyReplaceText {

    public static void main(String[] args) throws IOException {

        for (String fn : new String[]{"test1.txt", "test2.txt"}) {
            String s = new String(Files.readAllBytes(Paths.get(fn)));
            s = s.replace("Goodbye London!", "Hello New York!");
            try (FileWriter fw = new FileWriter(fn)) {
                fw.write(s);
            }
        }
    }
}



Python: import fileinput

for line in fileinput.input(inplace=True):
    print(line.replace('Goodbye London!', 'Hello New York!'), end='')
Task: Globally replace text in several files




Go: package main

import (
    "bytes"
    "io/ioutil"
    "log"
    "os"
)

func main() {
    gRepNFiles("Goodbye London!", "Hello New York!", []string{
        "a.txt",
        "b.txt",
        "c.txt",
    })
}

func gRepNFiles(olds, news string, files []string) {
    oldb := []byte(olds)
    newb := []byte(news)
    for _, fn := range files {
        if err := gRepFile(oldb, newb, fn); err != nil {
            log.Println(err)
        }
    }
}

func gRepFile(oldb, newb []byte, fn string) (err error) {
    var f *os.File
    if f, err = os.OpenFile(fn, os.O_RDWR, 0); err != nil {
        return
    }
    defer func() {
        if cErr := f.Close(); err == nil {
            err = cErr
        }
    }()
    var b []byte
    if b, err = ioutil.ReadAll(f); err != nil {
        return
    }
    if bytes.Index(b, oldb) < 0 {
        return
    }
    r := bytes.Replace(b, oldb, newb, -1)
    if err = f.Truncate(0); err != nil {
        return
    }
    _, err = f.WriteAt(r, 0)
    return
}




Python: import fileinput

for line in fileinput.input(inplace=True):
    print(line.replace('Goodbye London!', 'Hello New York!'), end='')