// System Command Output. Nigel Galloway: October 6th., 2020
let n=new System.Diagnostics.Process(StartInfo=System.Diagnostics.ProcessStartInfo(RedirectStandardOutput=true,RedirectStandardError=true,UseShellExecute=false,
          FileName= @"C:\Program Files (x86)\Microsoft Visual Studio\2019\BuildTools\Common7\IDE\CommonExtensions\Microsoft\FSharp\fsc.exe",Arguments="--help"))
n.Start()
printfn "%s" ((n.StandardOutput).ReadToEnd())
n.Close()


USING: io.encodings.utf8 io.launcher ;
"echo hello" utf8 [ contents ] with-process-reader .


s" ps " system                                 \ Output  only
                                 \ read via pipe  into buffer
create buffer 266 allot
s" ps " r/o open-pipe   throw
dup buffer swap  256 swap
read-file throw
swap close-pipe throw drop

buffer swap  type          \ output  is the  same  like  above


' FB 1.05.0 Win64

'capture the output of the 'dir' command and print it to a text file

Open "dir_output.txt" For Output As #1
Open Pipe "dir" For Input As #2
Dim li As String

While Not Eof(2)
  Line Input #2, li
  Print #1, li
Wend

Close #2
Close #1
End


include "NSLog.incl"

local fn ObserverOne( ref as NotificationRef )
FileHandleRef fh = fn NotificationObject( ref )
CFDataRef    dta = fn FileHandleAvailableData( fh )

if ( fn DataLength( dta ) > 0 )
CFStringRef string = fn StringWithData( dta, NSUTF8StringEncoding )
NSLog( @"%@", string )
FileHandleWaitForDataInBackgroundAndNotify( fh )
else
NotificationCenterRemoveObserver(  @fn ObserverOne, NSFileHandleDataAvailableNotification )
end if
end fn

local fn RunCommand( cmdStr as CFStringRef )
'~'1
TaskRef task = fn TaskInit
TaskSetExecutableURL( task, fn URLFileURLWithPath( @"/bin/sh" ) )
CFArrayRef arguments = fn ArrayWithObjects( @"-c", cmdStr, NULL )
TaskSetArguments( task, arguments )
PipeRef p = fn PipeInit
TaskSetStandardOutput( task, p )
FileHandleRef fh = fn PipeFileHandleForReading( p )
NotificationCenterAddObserver( @fn ObserverOne, NSFileHandleDataAvailableNotification, (FileHandleRef)fh )
fn TaskLaunch( task, NULL )
FileHandleWaitForDataInBackgroundAndNotify( fh )
end fn

fn RunCommand( @"man mdls | col -b" )

HandleEvents


Public Sub Main()
Dim sStore As String

Shell "ls" To sStore
Print sStore

End


[indent=4]
/*
  Get system command output, in Genie

  valac getSystemCommandOutput.gs
  ./getSystemCommandOutput
*/

init
    try
        // Blocking with output capture
        standard_output : string
        standard_error : string
        exit_status : int
        Process.spawn_command_line_sync("sh -c 'ls getSys*'",
            out standard_output, out standard_error, out exit_status)
        print standard_output
    except e : SpawnError
        stderr.printf("%s\n", e.message)


package main

import (
  "fmt"
  "log"
  "os/exec"
)

func main() {
  output, err := exec.Command("ls", "-l").CombinedOutput()
  if err != nil {
    log.Fatal(err)
  }
  fmt.Print(string(output))
}


#!/usr/bin/env stack
-- stack --resolver lts-8.15 --install-ghc runghc --package process

import System.Process (readProcess)

main :: IO ()
main = do
    -- get the output of the process as a list of lines
    results <- lines <$> readProcess "hexdump" ["-C", "/etc/passwd"] ""

    -- print each line in reverse
    mapM_ (putStrLn . reverse) results


#
# piped.icn, Get system command output
#
# Dedicated to the public domain
#
procedure main()
    # start with an empty list
    directory := []

    # ls for UNIX, dir for other, assume Windows
    command := if &features == "UNIX" then "ls" else "dir"

    # open command in pipe mode
    p := open(command, "p") | stop("Cannot open pipe for ", command)

    # read in results and append to list
    while put(directory, read(p))

    # display the fifth entry, if there is one
    write(\directory[5])

    close(p)
end


100 OPEN #1:"dirinfo.txt" ACCESS OUTPUT
110 SET DEFAULT CHANNEL 1
120 EXT "dir"
130 CLOSE #1
140 SET DEFAULT CHANNEL 0


   require 'task'
   <shell 'uname -imp'
┌─────────────────────┐
│x86_64 x86_64 x86_64 │
└─────────────────────┘


import java.io.*;
import java.util.*;

public class SystemCommand {

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

        String command = "cmd /c dir";
        Process p = Runtime.getRuntime().exec(command);

        try (Scanner sc = new Scanner(p.getInputStream())) {

            System.out.printf("Output of the command: %s %n%n", command);
            while (sc.hasNext()) {
                System.out.println(sc.nextLine());
            }
        }
    }
}


var commandOutput = exec('ls -gocart', { retAll:true });
puts(commandOutput.data);


// version 1.0.6

import java.util.Scanner

fun main(args: Array<String>) {
    val command = "cmd /c chcp"
    val p = Runtime.getRuntime().exec(command)
    val sc = Scanner(p.inputStream)
    println(sc.nextLine())
    sc.close()
}


local output = io.popen("echo Hurrah!")
print(output:read("*all"))


Module CheckIt {
      Dos "cd "+quote$(Dir$) +" & cmd /U /C  dir *.txt >txt.out";
      Document txt$
      Repeat {
            Wait 100
            Try  {
                  load.doc txt$, "txt.out"
            }
      } Until doc.len(txt$)<>0
      Report txt$
}
Checkit


/* Get system command output, neko */
var process_run = $loader.loadprim("[email protected]_run", 2);
var process_stdout_read = $loader.loadprim("[email protected]_stdout_read", 4);
var process_stderr_read = $loader.loadprim("[email protected]_stderr_read", 4);
var process_stdin_close = $loader.loadprim("[email protected]_stdin_close", 1);
var process_exit = $loader.loadprim("[email protected]_exit", 1);
var sys_exit = $loader.loadprim("[email protected]_exit", 1);

/* work buffer */
var bufsize = 1024;
var buffer = $smake(bufsize);

/* default command is ls, otherwise pass command line arguments */
var argc = $asize($loader.args);
var cmd = "ls";
var args;

/* Check command line arguments */
if argc > 0 {
    cmd = $loader.args[0];
}
if argc > 1 {
    args = $asub($loader.args, 1, argc - 1);
}

/* spawn process, with arguments */
var proc = process_run(cmd, args);

/* Close input channel - command might be waiting for input */
process_stdin_close(proc);

/* capture and print stdout */
var not_done = true;
var len = 0;
do {
    try {
        len = process_stdout_read(proc, buffer, 0, bufsize);
    } catch exc {
        not_done = false;
    }
    if (not_done) $print($ssub(buffer, 0, len));
} while not_done;

/* capture and print any stderr */
not_done = true;
len = 0;
do {
    try {
        len = process_stderr_read(proc, buffer, 0, bufsize);
    } catch exc {
        not_done = false;
    }
    if (not_done) $print($ssub(buffer, 0, len));
} while not_done;

/* Get the exit status */
var ps = process_exit(proc);
sys_exit(ps);


import osproc

# Output string and error code
let (lsalStr, errCode) = execCmdEx("ls -al")

echo "Error code: " & $errCode
echo "Output: " & lsalStr

# Output string only
let lsStr = execProcess("ls")

echo "Output: " & lsStr


class Test {
  function : Main(args : String[]) ~ Nil {
    output := System.Runtime->CommandOutput("ls -l");
    each(i : output) {
      output[i]->PrintLine();
    };
  }
}


/* Execute a system command and retrieve its output into a stem. */
  trace normal

/* Make the default values for the stem null strings. */
  text. = ''

/* Issue the system command.  "address command" is optional.) */
  address command 'ls -l | rxqueue'

/* Remember the return code from the command. */
  ls_rc = rc

/* Remember the number of lines created by the command. */
  text.0 = queued()

/* Fetch each line into a stem variable. */
  do t = 1 to text.0
    parse pull text.t
  end

/* Output each line in reverse order. */
  do t = text.0 to 1 by -1
    say text.t
  end

/* Exit with the system command's return code. */
exit ls_rc


my @directories = grep { chomp; -d } `ls`;
for (@directories) {
chomp;
...; # Operate on directories
}


without js -- system_exec, file i/o
constant tmp = "hostname.txt",
         cmd = iff(platform()=WINDOWS?"hostname":"uname -n")
{} = system_exec(sprintf("%s > %s",{cmd,tmp}),4)
string host = trim(get_text(tmp))
{} = delete_file(tmp)
?host


"hostname.txt" var hname
"hostname > " hname chain cmd
hname "r" fopen
dup fgets print fclose
"del " hname chain cmd


: (in '(uname "-om") (line T))
-> "aarch64 Android"


If OpenConsole("ls")
  rp=RunProgram("ls", "-l", "",#PB_Program_Open|#PB_Program_Read)
  While ProgramRunning(rp)
    If AvailableProgramOutput(rp)
      r$+ReadProgramString(rp)+#LF$
    EndIf
  Wend
  CloseProgram(rp)
  PrintN(r$)
  Input()
EndIf


/O> $ /
... import subprocess
... string_to_stack(str(subprocess.check_output('ls'),encoding='utf-8'))
... / python
... reverse echo$
...

ykq.kcudeltrut
yrdnus
yp.yrekcauq
ykq.Xsnoisnetxe
ykq.targib
fdp.yrekcauQ fo kooB ehT
fdp.tnirp rof yrekcauQ fo kooB ehT
txt.TSRIF EM DAER
fdp.ecnerefeR kciuQ yrekcauQ


system("wc -l /etc/passwd /etc/group", intern = TRUE)


#lang racket/base

(require racket/system
         (only-in racket/port with-output-to-string)
         tests/eli-tester)

(test
 ;; system runs command and outputs to current output port (which is stdout unless we catch it)
 (system "ls /etc/motd") => #t
 ;; it throws an error on non-zero exit code (so I need to catch it in this error handler)
 (system "false") => #f       ; nothing printed to stdout/stderr
 (system "ls /etc/mosh") => #f ; error report printed to stderr
 ;; output can be captured by redirecting stdout/stderr (which are known as current-output-port and
 ;; current-error-port in racket parlance).
 ;; the command printed a \n, so there is a newline captured by the system command
 (with-output-to-string (λ () (system "ls /etc/motd"))) => "/etc/motd\n"
 ;; no \n is captured when none is captured
 (with-output-to-string (λ () (system "echo -n foo"))) => "foo"
 ;; error is still not captured (it's still printed to stderr)
 (with-output-to-string (λ () (system "echo -n foo; echo bar 1>&2"))) => "foo"
 ;; we can capture both with:
 (let* ((out-str-port (open-output-string))
        (err-str-port (open-output-string))
        (system-rv
         (parameterize ((current-output-port out-str-port) (current-error-port err-str-port))
           (system "echo -n foo; echo bar 1>&2"))))
   (values system-rv (get-output-string out-str-port) (get-output-string err-str-port)))
 => (values #t "foo" "bar\n"))


say run($command, $arg1, $arg2, :out).out.slurp;


/*REXX program  executes a  system command  and displays the results  (from an array).  */
parse arg xxxCmd                                 /*obtain the (system) command from  CL.*/
trace off                                        /*suppress REXX error msgs for fails.  */
@.= 0                                            /*assign default in case ADDRESS fails.*/
address  system  xxxCmd  with  output  stem  @.  /*issue/execute the command and parms. */
if rc\==0  then  say  copies('─', 40)      ' return code '     rc     " from: "     xxxCmd
                                                 /* [↑]  display if an  error  occurred.*/
           do #=1  for @.0                       /*display the output from the command. */
           say strip(@.#, 'T')                   /*display one line at a time──►terminal*/
           end   /*#*/                           /* [↑]  displays all the output.       */
exit 0                                           /*stick a fork in it,  we're all done. */


a$ = shell$("dir") ' Returns the directory info into a$
print a$    ' prints the directory


use std::process::Command;
use std::io::{Write, self};

fn main() {
    let output = Command::new("/bin/cat")
                            .arg("/etc/fstab")
                            .output()
                            .expect("failed to execute process");

    io::stdout().write(&output.stdout);
}


import scala.io.Source

val command = "cmd /c echo Time at %DATE% %TIME%"
val p = Runtime.getRuntime.exec(command)
val sc = Source.fromInputStream(p.getInputStream)
println(sc.mkString)


var output = `ls`             # `output` is a string
var lines  = `ls`.lines       # `lines` is an array


program shellout, rclass
tempfile f
tempname m
shell `0' > `f'
file open `m' using "`f'", read binary
file seek `m' eof
file seek `m' query
local n=r(loc)
if `n'>0 {
	file seek `m' tof
	file read `m' %`n's s
	file close `m'
	return local out "`s'"
}
end


import Foundation

let process = Process()

process.launchPath = "/usr/bin/env"
process.arguments = ["pwd"]

let pipe = Pipe()
process.standardOutput = pipe

process.launch()

let data = pipe.fileHandleForReading.readDataToEndOfFile()
let output = String.init(data: data, encoding: String.Encoding.utf8)

print(output!)


val useOS =  fn input =>
  let
   val text       =   String.translate (fn #"\"" => "\\\""|n=>str n )  input ;
   val shellCommand = " echo " ^ text ^ "| gzip -c " ;
   val fname      =  "/tmp/fConv" ^ (String.extract (Time.toString (Posix.ProcEnv.time()),7,NONE) );
   val me         = (  Posix.FileSys.mkfifo
                               (fname,
			        Posix.FileSys.S.flags [ Posix.FileSys.S.irusr,Posix.FileSys.S.iwusr ]
			       ) ;
                       Posix.Process.fork ()
		     ) ;
  in
   if (Option.isSome me) then
     let
        val fin =BinIO.openIn fname
     in
        ( Posix.Process.sleep (Time.fromReal 0.1) ;
          BinIO.inputAll fin  before
	  (BinIO.closeIn fin ; OS.FileSys.remove fname )
	)
     end
   else
     ( OS.Process.system (  shellCommand ^ " > " ^ fname  ^ " 2>&1 "     ) ;
       Word8Vector.fromList [] before OS.Process.exit OS.Process.success
     )
  end;


set data [exec ls -l]
puts "read [string length $data] bytes and [llength [split $data \n]] lines"


> decl iodevice iod
> decl string<> arg
> append "ifconfig" arg
> set iod (ursa.util.process.start arg)
> decl string<> output
> set output (iod.readlines)
> for (decl int i) (< i (size output)) (inc i)
..	out output<i> endl console
..end for
lo0: flags=8049<UP,LOOPBACK,RUNNING,MULTICAST> mtu 16384
	options=3<RXCSUM,TXCSUM>
	inet6 ::1 prefixlen 128
	inet 127.0.0.1 netmask 0xff000000
	inet6 fe80::1%lo0 prefixlen 64 scopeid 0x1
	nd6 options=1<PERFORMNUD>
gif0: flags=8010<POINTOPOINT,MULTICAST> mtu 1280
stf0: flags=0<> mtu 1280
en0: flags=8863<UP,BROADCAST,SMART,RUNNING,SIMPLEX,MULTICAST> mtu 1500
	options=27<RXCSUM,TXCSUM,VLAN_MTU,TSO4>
	ether d4:9a:20:b8:8d:2c
	nd6 options=1<PERFORMNUD>
	media: autoselect
	status: inactive
en1: flags=8863<UP,BROADCAST,SMART,RUNNING,SIMPLEX,MULTICAST> mtu 1500
	ether 00:26:08:e0:67:cc
	inet6 fe80::226:8ff:fee0:67cc%en1 prefixlen 64 scopeid 0x5
	inet 172.20.30.66 netmask 0xffffff00 broadcast 172.20.30.255
	nd6 options=1<PERFORMNUD>
	media: autoselect
	status: active
fw0: flags=8863<UP,BROADCAST,SMART,RUNNING,SIMPLEX,MULTICAST> mtu 4078
	lladdr d4:9a:20:ff:fe:b8:8d:2c
	nd6 options=1<PERFORMNUD>
	media: autoselect <full-duplex>
	status: inactive
p2p0: flags=8843<UP,BROADCAST,RUNNING,SIMPLEX,MULTICAST> mtu 2304
	ether 02:26:08:e0:67:cc
	media: autoselect
	status: inactive
>


For Each line In ExecCmd("ipconfig /all")
    Wscript.Echo line
Next

'Execute the given command and return the output in a text array.
Function ExecCmd(cmd)

    'Execute the command
    Dim wso : Set wso = CreateObject("Wscript.Shell")
    Dim exec : Set exec = wso.Exec(cmd)
    Dim res : res = ""

    'Read all result text from standard output
    Do
        res = res & VbLf & exec.StdOut.ReadLine
    Loop Until exec.StdOut.AtEndOfStream

    'Return as a text array
    ExecCmd = Split(Mid(res,2),vbLf)
End Function


Module Module1

    Sub Main()
        Dim proccess As New Process
        Dim startInfo As New ProcessStartInfo

        startInfo.WindowStyle = ProcessWindowStyle.Hidden
        startInfo.FileName = "cmd.exe"
        startInfo.Arguments = "/c echo Hello World"
        startInfo.RedirectStandardOutput = True
        startInfo.UseShellExecute = False

        proccess.StartInfo = startInfo
        proccess.Start()

        Dim output = proccess.StandardOutput.ReadToEnd
        Console.WriteLine("Output is {0}", output)
    End Sub

End Module


/* get_system_command_output.wren */
class Command {
    foreign static output(name, param) // the code for this is provided by Go
}

System.print(Command.output("ls", "-ls"))


// Rosetta Code problem: https://www.rosettacode.org/wiki/Get_system_command_output
// by Jjuanhdez, 06/2022

if peek$("os") = "unix" then
  c$ = "ls *"
else        //"windows"
  c$ = "dir *.*"
fi

open("dir_output.txt") for writing as #1
print #1 system$(c$)
close #1


zkl: System.cmd("date >foo.txt")
0  // date return code
zkl: File("foo.txt").read().text
Wed Aug 20 00:28:55 PDT 2014


V board = [[‘ ’] * 8] * 8
V piece_list = [‘R’, ‘N’, ‘B’, ‘Q’, ‘P’]

F place_kings(&brd)
   L
      V (rank_white, file_white, rank_black, file_black) = (random:(0 .. 7), random:(0 .. 7), random:(0 .. 7), random:(0 .. 7))
      V diff_list = [abs(rank_white - rank_black), abs(file_white - file_black)]
      I sum(diff_list) > 2 | Set(diff_list) == Set([0, 2])
         (brd[rank_white][file_white], brd[rank_black][file_black]) = (Char(‘K’), Char(‘k’))
         L.break

F pawn_on_promotion_square(pc, pr)
   I pc == ‘P’ & pr == 0
      R 1B
   E I pc == ‘p’ & pr == 7
      R 1B
   R 0B

F populate_board(&brd, wp, bp)
   L(x) 2
      Int piece_amount
      [Char] pieces
      I x == 0
         piece_amount = wp
         pieces = :piece_list
      E
         piece_amount = bp
         pieces = :piece_list.map(s -> s.lowercase())
      L piece_amount != 0
         V (piece_rank, piece_file) = (random:(0 .. 7), random:(0 .. 7))
         V piece = random:choice(pieces)
         I brd[piece_rank][piece_file] == ‘ ’ & pawn_on_promotion_square(piece, piece_rank) == 0B
            brd[piece_rank][piece_file] = piece
            piece_amount--

F fen_from_board(brd)
   V fen = ‘’
   L(x) brd
      V n = 0
      L(y) x
         I y == ‘ ’
            n++
         E
            I n != 0
               fen ‘’= String(n)
            fen ‘’= y
            n = 0
      I n != 0
         fen ‘’= String(n)
      fen ‘’= I fen.count(‘/’) < 7 {‘/’} E ‘’
   fen ‘’= " w - - 0 1\n"
   R fen

V (piece_amount_white, piece_amount_black) = (random:(0 .. 15), random:(0 .. 15))
place_kings(&board)
populate_board(&board, piece_amount_white, piece_amount_black)
print(fen_from_board(board))
L(x) board
   print(‘[’x.map(c -> ‘'’c‘'’).join(‘, ’)‘]’)


DEFINE BOARDSIZE="64"
DEFINE EMPTY="'."

BYTE FUNC AbsDist(BYTE a,b)
  IF a>b THEN RETURN (a-b) FI
RETURN (b-a)

BYTE FUNC GetPiece(BYTE ARRAY board BYTE x,y)
RETURN (board(x+y*8))

PROC PutPiece(BYTE ARRAY board BYTE x,y,piece)
  board(x+y*8)=piece
RETURN

PROC PrintBoard(BYTE ARRAY board)
  BYTE i,j,c

  FOR j=0 TO 7
  DO
    FOR i=0 TO 7
    DO
      c=GetPiece(board,i,j)
      Put(c)
    OD
    PutE()
  OD
RETURN

PROC Append(CHAR ARRAY s CHAR c)
  s(0)==+1
  s(s(0))=c
RETURN

PROC ExportToFen(BYTE ARRAY board CHAR ARRAY fen)
  CHAR ARRAY s=" w - - 0 1"
  INT x,y
  BYTE count,p

  fen(0)=0
  FOR y=0 TO 7
  DO
    x=0
    WHILE x<8
    DO
      count=0
      WHILE x<8 AND GetPiece(board,x,y)=EMPTY
      DO
        x==+1 count==+1
      OD
      IF count>0 THEN
        Append(fen,'0+count)
      ELSE
        p=GetPiece(board,x,y)
        Append(fen,p)
        x==+1
      FI
    OD
    IF y<7 THEN
      Append(fen,'/)
    FI
  OD

  FOR x=1 TO s(0)
  DO
    Append(fen,s(x))
  OD
RETURN

PROC PutKings(BYTE ARRAY board)
  BYTE x1,y1,x2,y2
  DO
    x1=Rand(8) y1=Rand(8)
    x2=Rand(8) y2=Rand(8)
    IF AbsDist(x1,x2)>1 AND AbsDist(y1,y2)>1 THEN
      PutPiece(board,x1,y1,'K)
      PutPiece(board,x2,y2,'k)
      RETURN
    FI
  OD
RETURN

PROC PutPieces(BYTE ARRAY board CHAR ARRAY pieces)
  BYTE i,x,y,p

  FOR i=1 TO pieces(0)
  DO
    p=pieces(i)
    DO
      x=Rand(8)
      IF p='P OR p='p THEN
        y=Rand(6)+1
      ELSE
        y=Rand(8)
      FI
    UNTIL GetPiece(board,x,y)=EMPTY
    OD
    PutPiece(board,x,y,p)
  OD
RETURN

PROC Generate(BYTE ARRAY board CHAR ARRAY pieces)
  SetBlock(board,BOARDSIZE,EMPTY)
  PutKings(board)
  PutPieces(board,pieces)
RETURN

PROC Test(CHAR ARRAY pieces)
  BYTE ARRAY board(BOARDSIZE)
  CHAR ARRAY fen(256)

  Generate(board,pieces)
  PrintBoard(board)
  ExportToFen(board,fen)
  PrintE(fen) PutE()
RETURN

PROC Main()
  Test("PPPPPPPPBBNNQRRppppppppbbnnqrr")
  Test("PPBNQRppbnqr")
RETURN


#include <stdio.h>
#include <math.h>
#include <string.h>
#include <stdlib.h>
#include <time.h>

#define TRUE 1
#define FALSE 0

typedef int bool;

char grid[8][8];

void placeKings() {
    int r1, r2, c1, c2;
    for (;;) {
        r1 = rand() % 8;
        c1 = rand() % 8;
        r2 = rand() % 8;
        c2 = rand() % 8;
        if (r1 != r2 && abs(r1 - r2) > 1 && abs(c1 - c2) > 1) {
            grid[r1][c1] = 'K';
            grid[r2][c2] = 'k';
            return;
        }
    }
}

void placePieces(const char *pieces, bool isPawn) {
    int n, r, c;
    int numToPlace = rand() % strlen(pieces);
    for (n = 0; n < numToPlace; ++n) {
        do {
            r = rand() % 8;
            c = rand() % 8;
        }
        while (grid[r][c] != 0 || (isPawn && (r == 7 || r == 0)));
        grid[r][c] = pieces[n];
    }
}

void toFen() {
    char fen[80], ch;
    int r, c, countEmpty = 0, index = 0;
    for (r = 0; r < 8; ++r) {
        for (c = 0; c < 8; ++c) {
            ch = grid[r][c];
            printf("%2c ", ch == 0 ? '.' : ch);
            if (ch == 0) {
                countEmpty++;
            }
            else {
                if (countEmpty > 0) {
                    fen[index++] = countEmpty + 48;
                    countEmpty = 0;
                }
                fen[index++] = ch;
            }
        }
        if (countEmpty > 0) {
            fen[index++] = countEmpty + 48;
            countEmpty = 0;
        }
        fen[index++]= '/';
        printf("\n");
    }
    strcpy(fen + index, " w - - 0 1");
    printf("%s\n", fen);
}

char *createFen() {
    placeKings();
    placePieces("PPPPPPPP", TRUE);
    placePieces("pppppppp", TRUE);
    placePieces("RNBQBNR", FALSE);
    placePieces("rnbqbnr", FALSE);
    toFen();
}

int main() {
    srand(time(NULL));
    createFen();
    return 0;
}


#include <ctime>
#include <iostream>
#include <string>
#include <algorithm>

class chessBoard {
public:
    void generateRNDBoard( int brds ) {
        int a, b, i; char c;
        for( int cc = 0; cc < brds; cc++ ) {
            memset( brd, 0, 64 );
            std::string pieces = "PPPPPPPPNNBBRRQKppppppppnnbbrrqk";
            random_shuffle( pieces.begin(), pieces.end() );

            while( pieces.length() ) {
                i = rand() % pieces.length(); c = pieces.at( i );
                while( true ) {
                    a = rand() % 8; b = rand() % 8;
                    if( brd[a][b] == 0 ) {
                        if( c == 'P' && !b || c == 'p' && b == 7 ||
                          ( ( c == 'K' || c == 'k' ) && search( c == 'k' ? 'K' : 'k', a, b ) ) ) continue;
                        break;
                    }
                }
                brd[a][b] = c;
                pieces = pieces.substr( 0, i ) + pieces.substr( i + 1 );
            }
            print();
        }
    }
private:
    bool search( char c, int a, int b ) {
        for( int y = -1; y < 2; y++ ) {
            for( int x = -1; x < 2; x++ ) {
                if( !x && !y ) continue;
                if( a + x > -1 && a + x < 8 && b + y >-1 && b + y < 8 ) {
                    if( brd[a + x][b + y] == c ) return true;
                }
            }
        }
        return false;
    }
    void print() {
        int e = 0;
        for( int y = 0; y < 8; y++ ) {
            for( int x = 0; x < 8; x++ ) {
                if( brd[x][y] == 0 ) e++;
                else {
                    if( e > 0 ) { std::cout << e; e = 0; }
                    std::cout << brd[x][y];
                }
            }
            if( e > 0 ) { std::cout << e; e = 0; }
            if( y < 7 ) std::cout << "/";
        }
        std::cout << " w - - 0 1\n\n";

        for( int y = 0; y < 8; y++ ) {
            for( int x = 0; x < 8; x++ ) {
                if( brd[x][y] == 0 ) std::cout << ".";
                else std::cout << brd[x][y];
            }
            std::cout << "\n";
        }

        std::cout << "\n\n";
    }
    char brd[8][8];
};
int main( int argc, char* argv[] ) {
    srand( ( unsigned )time( 0 ) );
    chessBoard c;
    c.generateRNDBoard( 2 );
    return 0;
}


def hasNK(board, a, b)
    (-1..1).each do |g|
        (-1..1).each do |f|
            aa = a + f; bb = b + g
            if (0..7).includes?(aa) && (0..7).includes?(bb)
                p = board[aa + 8 * bb]
                return true if p == "K" || p == "k"
            end
        end
    end
    return false
end

def generateBoard(board, pieces)
    pieces.each_char do |p|
        while true
            a = rand(8); b = rand(8)
            next  if ( (b == 0 || b == 7) && (p == "P" || p == "p") ) ||
               ( (p == "k" || p == "K") && hasNK(board, a, b) )
            break if board[a + b * 8] == '.'
        end
        board[a + b * 8] = p
    end
end

pieces = "ppppppppkqrrbbnnPPPPPPPPKQRRBBNN"
11.times do
    e = pieces.size - 1
    while e > 0
        p = rand(e); t = pieces[e]
        #pieces[e] = pieces[p]; pieces[p] = t; e -= 1 # in Ruby
        pieces = pieces.sub(e, pieces[p])             # in Crystal because
        pieces = pieces.sub(p, t); e -= 1             # strings immutable
    end
end

# No 'nil' for Crystal arrays; use '.' for blank value
board = Array.new(64, '.'); generateBoard(board, pieces)
puts
e = 0
8.times do |j| row_j = j * 8
    8.times do |i|
        board[row_j + i ] == '.' ? (e += 1) :
            ( (print(e); e = 0) if e > 0
            print board[row_j + i] )
    end
    (print(e); e = 0) if e > 0
    print("/") if j < 7
end

print(" w - - 0 1\n")
8.times do |j| row_j = j * 8
  8.times { |i| board[row_j + i] == '.' ? print(".") : print(board[row_j + i]) }
  puts
end

# Simpler for same output
8.times{ |row| puts board[row*8..row*8 + 7].join("") }


USING: combinators.short-circuit grouping io kernel math
math.parser math.ranges math.vectors prettyprint random
sequences sets splitting.monotonic strings ;
IN: rosetta-code.random-chess-position

<PRIVATE

CONSTANT: pieces "RNBQBNRPPPPPPPPrnbqbnrpppppppp"
CONSTANT: empty CHAR: .

: <empty-board> ( -- seq ) 64 [ empty ] "" replicate-as ;
: empty-index ( seq -- n ) empty swap indices random ;
: place ( seq elt n -- seq' ) rot [ set-nth ] keep ;

! return a list of indices that are adjacent to n
: adj ( n -- seq )
    [ 1 - ] [ 1 + ] bi [a,b] { 8 8 8 } [ v- ] 2keep dupd v+
    append append ;

: rand-non-adjacent ( m -- n ) 64 <iota> swap adj diff random ;

: place-kings ( seq -- seq' )
    CHAR: K over empty-index [ place ] keep [ CHAR: k ] dip
    rand-non-adjacent place ;

: non-pawn ( seq elt -- seq' ) over empty-index place ;

! prevent placing of pawns in ranks 1 and 8
: pawn ( seq elt -- seq' )
    over empty swap indices
    [ { [ 7 > ] [ 56 < ] } 1&& ] filter random place ;

: place-piece ( seq -- seq' )
    pieces random dup "Pp" member? [ pawn ] [ non-pawn ] if ;

PRIVATE>

: position ( -- seq )
    <empty-board> place-kings 30 random [ place-piece ] times ;

: position. ( seq -- )
    [ 1string ] { } map-as 8 group simple-table. ;

: position>fen ( seq -- seq' )
    8 group [
        [ = ] monotonic-split
        [ dup first empty = [ length number>string ] when ]
        map concat
    ] map "/" join "/ w - - 0 1" append ;

: random-chess-position-demo ( -- )
    position [ position. ] [ position>fen print ] bi ;

MAIN: random-chess-position-demo


Dim Shared As Byte grid(8, 8), r, c

Sub placeKings()
    Dim As Byte r1, r2, c1, c2

    Do
        r1 = Int(Rnd*8)
        c1 = Int(Rnd*8)
        r2 = Int(Rnd*8)
        c2 = Int(Rnd*8)
        If (r1 <> r2 And Abs(r1 - r2) > 1 And Abs(c1 - c2) > 1) Then
            grid(r1, c1) = Asc("K")
            grid(r2, c2) = Asc("k")
            Return
        End If
    Loop
End Sub

Sub placePieces(pieces As String, isPawn As Byte)
    Dim numToPlace As Byte = Int(Rnd*(Len(pieces)))

    For n As Byte = 0 To numToPlace-1
        Do
            r = Int(Rnd*8)
            c = Int(Rnd*8)
        Loop Until(Not(grid(r, c) Or (isPawn And (r = 7 Or r = 0))))
        grid(r, c) = Asc(Mid(pieces, n, 1))
    Next n
End Sub

Sub toFen()
    Dim As Byte ch, countEmpty = 0
    Dim As String fen

    For r = 0 To 8-1
        For c = 0 To 8-1
            ch = grid(r, c)
            If ch <> 0 Then
                Print " " & Chr(ch);
            Else
                Print " .";
            End If
            If ch = 0 Then
                countEmpty += 1
            Else
                If countEmpty > 0 Then
                    fen += Chr(countEmpty + 48)
                    countEmpty = 0
                End If
                fen += Chr(ch)
            End If
        Next c
        If countEmpty > 0 Then
            fen += Chr(countEmpty + 48)
            countEmpty = 0
        End If
        fen += "/"
        Print
    Next r
    fen += " w - - 0 1"
    Print fen
End Sub

Randomize Timer
placeKings()
placePieces("PPPPPPPP", True)
placePieces("pppppppp", True)
placePieces("RNBQBNR", False)
placePieces("rnbqbnr", False)
toFen()
Sleep


package main

import (
    "fmt"
    "math/rand"
    "strconv"
    "strings"
    "time"
)

var grid [8][8]byte

func abs(i int) int {
    if i >= 0 {
        return i
    } else {
        return -i
    }
}

func createFen() string {
    placeKings()
    placePieces("PPPPPPPP", true)
    placePieces("pppppppp", true)
    placePieces("RNBQBNR", false)
    placePieces("rnbqbnr", false)
    return toFen()
}

func placeKings() {
    for {
        r1 := rand.Intn(8)
        c1 := rand.Intn(8)
        r2 := rand.Intn(8)
        c2 := rand.Intn(8)
        if r1 != r2 && abs(r1-r2) > 1 && abs(c1-c2) > 1 {
            grid[r1][c1] = 'K'
            grid[r2][c2] = 'k'
            return
        }
    }
}

func placePieces(pieces string, isPawn bool) {
    numToPlace := rand.Intn(len(pieces))
    for n := 0; n < numToPlace; n++ {
        var r, c int
        for {
            r = rand.Intn(8)
            c = rand.Intn(8)
            if grid[r][c] == '\000' && !(isPawn && (r == 7 || r == 0)) {
                break
            }
        }
        grid[r][c] = pieces[n]
    }
}

func toFen() string {
    var fen strings.Builder
    countEmpty := 0
    for r := 0; r < 8; r++ {
        for c := 0; c < 8; c++ {
            ch := grid[r][c]
            if ch == '\000' {
                ch = '.'
            }
            fmt.Printf("%2c ", ch)
            if ch == '.' {
                countEmpty++
            } else {
                if countEmpty > 0 {
                    fen.WriteString(strconv.Itoa(countEmpty))
                    countEmpty = 0
                }
                fen.WriteByte(ch)
            }
        }
        if countEmpty > 0 {
            fen.WriteString(strconv.Itoa(countEmpty))
            countEmpty = 0
        }
        fen.WriteString("/")
        fmt.Println()
    }
    fen.WriteString(" w - - 0 1")
    return fen.String()
}

func main() {
    rand.Seed(time.Now().UnixNano())
    fmt.Println(createFen())
}


{-# LANGUAGE LambdaCase, TupleSections #-}

module RandomChess
( placeKings
, placePawns
, placeRemaining
, emptyBoard
, toFen
, ChessBoard
, Square (..)
, BoardState (..)
, getBoard
)
where

import Control.Monad.State (State, get, gets, put)
import Data.List (find, sortBy)
import System.Random (Random, RandomGen, StdGen, random, randomR)

type Pos = (Char, Int)

type ChessBoard = [(Square, Pos)]

data PieceRank  = King | Queen | Rook | Bishop | Knight | Pawn
  deriving (Enum, Bounded, Show, Eq, Ord)
data PieceColor = Black | White
  deriving (Enum, Bounded, Show, Eq, Ord)

data Square = ChessPiece PieceRank PieceColor | EmptySquare
  deriving (Eq, Ord)

type PieceCount = [(Square, Int)]

data BoardState = BoardState { board :: ChessBoard , generator :: StdGen }

instance Show Square where
  show (ChessPiece King   Black) = "♚"
  show (ChessPiece Queen  Black) = "♛"
  show (ChessPiece Rook   Black) = "♜"
  show (ChessPiece Bishop Black) = "♝"
  show (ChessPiece Knight Black) = "♞"
  show (ChessPiece Pawn   Black) = "♟"
  show (ChessPiece King   White) = "♔"
  show (ChessPiece Queen  White) = "♕"
  show (ChessPiece Rook   White) = "♖"
  show (ChessPiece Bishop White) = "♗"
  show (ChessPiece Knight White) = "♘"
  show (ChessPiece Pawn   White) = "♙"
  show EmptySquare               = " "

instance Random PieceRank where
  randomR (a, b) g = case randomR (fromEnum a, fromEnum b) g of
    (x, g'') -> (toEnum x, g'')
  random = randomR (minBound, maxBound)

instance Random PieceColor where
  randomR (a, b) g = case randomR (fromEnum a, fromEnum b) g of
    (x, g'') -> (toEnum x, g'')
  random = randomR (minBound, maxBound)

fullBoard :: PieceCount
fullBoard =
  [ (ChessPiece King Black  , 1)
  , (ChessPiece Queen Black , 1)
  , (ChessPiece Rook Black  , 2)
  , (ChessPiece Bishop Black, 2)
  , (ChessPiece Knight Black, 2)
  , (ChessPiece Pawn Black  , 8)
  , (ChessPiece King White  , 1)
  , (ChessPiece Queen White , 1)
  , (ChessPiece Rook White  , 2)
  , (ChessPiece Bishop White, 2)
  , (ChessPiece Knight White, 2)
  , (ChessPiece Pawn White  , 8)
  , (EmptySquare            , 32)
  ]

emptyBoard :: ChessBoard
emptyBoard = fmap (EmptySquare,) . (,) <$> ['a'..'h'] <*> [1..8]

replaceSquareByPos :: (Square, Pos) -> ChessBoard -> ChessBoard
replaceSquareByPos e@(_, p) = fmap (\x -> if p == snd x then e else x)

isPosOccupied :: Pos -> ChessBoard -> Bool
isPosOccupied p = occupied . find (\x -> p == snd x)
 where
  occupied (Just (EmptySquare, _)) = False
  occupied _                       = True

isAdjacent :: Pos -> Pos -> Bool
isAdjacent (x1, y1) (x2, y2) =
  let upOrDown    = (pred y1 == y2 || succ y1 == y2)
      leftOrRight = (pred x1 == x2 || succ x1 == x2)
  in  (x2 == x1 && upOrDown)
        || (pred x1 == x2 && upOrDown)
        || (succ x1 == x2 && upOrDown)
        || (leftOrRight && y1 == y2)

fen :: Square -> String
fen (ChessPiece King   Black) = "k"
fen (ChessPiece Queen  Black) = "q"
fen (ChessPiece Rook   Black) = "r"
fen (ChessPiece Bishop Black) = "b"
fen (ChessPiece Knight Black) = "n"
fen (ChessPiece Pawn   Black) = "p"
fen (ChessPiece King   White) = "K"
fen (ChessPiece Queen  White) = "Q"
fen (ChessPiece Rook   White) = "R"
fen (ChessPiece Bishop White) = "B"
fen (ChessPiece Knight White) = "N"
fen (ChessPiece Pawn   White) = "P"

boardSort :: (Square, Pos) -> (Square, Pos) -> Ordering
boardSort (_, (x1, y1)) (_, (x2, y2)) | y1 < y2  = GT
                                      | y1 > y2  = LT
                                      | y1 == y2 = compare x1 x2

toFen :: ChessBoard -> String
toFen [] = " w - - 0 1" <> []
toFen b = scanRow (fst <$> take 8 b) 0
  where
    scanRow [] 0               = nextRow
    scanRow [] n               = show n <> nextRow
    scanRow (EmptySquare:xs) n = scanRow xs (succ n)
    scanRow (x:xs) 0           = nextPiece x xs
    scanRow (x:xs) n           = show n <> nextPiece x xs
    nextRow = "/" <> toFen (drop 8 b)
    nextPiece x xs = fen x <> scanRow xs 0

-- State functions
withStateGen :: (StdGen -> (a, StdGen)) -> State BoardState a
withStateGen f = do
  currentState <- get
  let gen1 = generator currentState
  let (x, gen2) = f gen1
  put (currentState {generator = gen2})
  pure x

randomPos :: State BoardState Pos
randomPos = do
  boardState <- gets board
  chr <- withStateGen (randomR ('a', 'h'))
  num <- withStateGen (randomR (1, 8))
  let pos = (chr, num)
  if isPosOccupied pos boardState then
    randomPos
  else
    pure pos

randomPiece :: State BoardState Square
randomPiece = ChessPiece <$> withStateGen random <*> withStateGen random

placeKings :: State BoardState ()
placeKings = do
  currentState <- get
  p1 <- randomPos
  p2 <- randomPos
  if p1 `isAdjacent` p2 || p1 == p2
    then placeKings
    else do
      let updatedBoard = replaceSquareByPos (ChessPiece King White, p1) $
            replaceSquareByPos (ChessPiece King Black, p2) (board currentState)
      put currentState { board = updatedBoard }

placePawns :: State BoardState ()
placePawns = withStateGen (randomR (1, 16)) >>= go
  where
    go :: Int -> State BoardState ()
    go 0 = pure ()
    go n = do
      currentState <- get
      pos <- randomPos
      color <- withStateGen random
      let pawn = ChessPiece Pawn color
      let currentBoard = board currentState
      if promoted color == snd pos || isPosOccupied pos currentBoard ||
                           enpassant color == snd pos || firstPos color == snd pos
        then go n
        else do
          put currentState { board = replaceSquareByPos (pawn, pos) currentBoard }
          go $ pred n
    promoted White = 8
    promoted Black = 1
    enpassant White = 5
    enpassant Black = 4
    firstPos White = 1
    firstPos Black = 8

placeRemaining :: State BoardState ()
placeRemaining =
  withStateGen (randomR (5, sum $ fmap snd remaining)) >>= go remaining
  where
    remaining = filter (\case
                         (ChessPiece King _, _) -> False
                         (ChessPiece Pawn _, _) -> False
                         (EmptySquare, _) -> False
                         _ -> True)
                        fullBoard

    go :: PieceCount -> Int -> State BoardState ()
    go _ 0 = pure ()
    go remaining n = do
      currentState <- get
      let currentBoard = board currentState
      position <- randomPos
      piece <- randomPiece
      if not (isPermitted piece) || isPosOccupied position currentBoard
        then go remaining n
        else do
          let updatedBoard = replaceSquareByPos (piece, position) currentBoard
          put currentState { board = updatedBoard }
          go (consume piece remaining) (pred n)
      where
        isPermitted p =
          case find ((==p) . fst) remaining of
            Just (_, count) -> count > 0
            Nothing         -> False
        consume p'' = fmap (\(p, c) -> if p == p'' then (p, pred c) else (p, c))

getBoard :: State BoardState ChessBoard
getBoard = gets (sortBy boardSort . board)


getlayout=:3 :0
  whilst. NB. first two positions are non-adjacent kings
    (0{pos) e. (1{pos)+(,-)1 7 8 9
  do.
    pos=: y?64
  end.
)

randboard=:3 :0
  n=: ?30  NB. number of non-king pieces on board
  layout=: getlayout 2+n   NB. where they go
  white=: 0 1,?n#2         NB. which ones are white?
  pawns=: 0 0,?n#2             NB. where are the pawns?
  pawns=: pawns * 1- white*layout e.56+i.8
  pawns=: pawns * 1-(1-white)*layout e.i.8
  ptyp=: 'pkqbjnPKQBJN'{~(6*white)+1 1,(1-2}.pawns)*2+?n#4
  8 8$ptyp layout}64#'.'
)

NB. fen compress a line
fen1=:3 :0
  for_n.8-i.8 do.
    y=. y rplc (#&'.';":) n
  end.
)

NB. translate 8x8 board to fen notation
NB. (just the task specific crippled fen)
b2fen=:3 :0
  (}.;|.<@(('/',fen1)"1) y),' w - - 0 1'
)

randfen=:[email protected]


import static java.lang.Math.abs;
import java.util.Random;

public class Fen {
    static Random rand = new Random();

    public static void main(String[] args) {
        System.out.println(createFen());
    }

    static String createFen() {
        char[][] grid = new char[8][8];

        placeKings(grid);
        placePieces(grid, "PPPPPPPP", true);
        placePieces(grid, "pppppppp", true);
        placePieces(grid, "RNBQBNR", false);
        placePieces(grid, "rnbqbnr", false);

        return toFen(grid);
    }

    static void placeKings(char[][] grid) {
        int r1, c1, r2, c2;
        while (true) {
            r1 = rand.nextInt(8);
            c1 = rand.nextInt(8);
            r2 = rand.nextInt(8);
            c2 = rand.nextInt(8);
            if (r1 != r2 && abs(r1 - r2) > 1 && abs(c1 - c2) > 1)
                break;
        }
        grid[r1][c1] = 'K';
        grid[r2][c2] = 'k';
    }

    static void placePieces(char[][] grid, String pieces, boolean isPawn) {
        int numToPlace = rand.nextInt(pieces.length());
        for (int n = 0; n < numToPlace; n++) {
            int r, c;
            do {
                r = rand.nextInt(8);
                c = rand.nextInt(8);

            } while (grid[r][c] != 0 || (isPawn && (r == 7 || r == 0)));

            grid[r][c] = pieces.charAt(n);
        }
    }

    static String toFen(char[][] grid) {
        StringBuilder fen = new StringBuilder();
        int countEmpty = 0;
        for (int r = 0; r < 8; r++) {
            for (int c = 0; c < 8; c++) {
                char ch = grid[r][c];
                System.out.printf("%2c ", ch == 0 ? '.' : ch);
                if (ch == 0) {
                    countEmpty++;
                } else {
                    if (countEmpty > 0) {
                        fen.append(countEmpty);
                        countEmpty = 0;
                    }
                    fen.append(ch);
                }
            }
            if (countEmpty > 0) {
                fen.append(countEmpty);
                countEmpty = 0;
            }
            fen.append("/");
            System.out.println();
        }
        return fen.append(" w - - 0 1").toString();
    }
}


Array.prototype.shuffle = function() {
  for (let i = this.length - 1; i > 0; i--) {
    let j = Math.floor(Math.random() * (i + 1));
    [this[i], this[j]] = [this[j], this[i]];
  }
}

function randomFEN() {

  let board = [];
  for (let x = 0; x < 8; x++) board.push('. . . . . . . .'.split(' '));

  function getRandPos() {
    return [Math.floor(Math.random() * 8), Math.floor(Math.random() * 8)];
  }

  function isOccupied(pos) {
    return board[pos[0]][pos[1]] != '.';
  }

  function isAdjacent(pos1, pos2) {
    if (pos1[0] == pos2[0] || pos1[0] == pos2[0]-1 || pos1[0] == pos2[0]+1)
    if (pos1[1] == pos2[1] || pos1[1] == pos2[1]-1 || pos1[1] == pos2[1]+1)
      return true;
    return false;
  }

  // place kings
  let wk, bk;
  do { wk = getRandPos(); bk = getRandPos(); }
  while (isAdjacent(wk, bk));
  board[wk[0]][wk[1]] = 'K';
  board[bk[0]][bk[1]] = 'k';

  // get peaces
  let peaces = [];
  let names = 'PRNBQ';
  function pick() {
    for (x = 1; x < Math.floor(Math.random() * 32); x++)
      peaces.push(names[Math.floor(Math.random() * names.length)]);
  }
  pick();
  names = names.toLowerCase();
  pick();
  peaces.shuffle();

  // place peaces
  while (peaces.length > 0) {
    let p = peaces.shift(), pos;
    // paws: cannot be placed in bottom or top row
    if (p == 'p' || p == 'P')
      do { pos = getRandPos() }
      while (isOccupied(pos) || pos[0] == 0 || pos[0] == 7);
    // everything else
    else do { pos = getRandPos(); } while (isOccupied(pos));
    board[pos[0]][pos[1]] = p;
  }

  // write FEN
  let fen = [];
  for (x = 0; x < board.length; x++) {
    let str ='', buf = 0;
    for (let y = 0; y < board[x].length; y++)
      if (board[x][y] == '.') buf++;
      else {
        if (buf > 0) { str += buf; buf = 0; }
        str += board[x][y];
      }
    if (buf > 0) str += buf;
    fen.push(str);
  }
  fen = fen.join('/') + ' w - - 0 1';
  console.table(board); // for demonstrating purpose
  return fen;
}

// example
console.log(randomFEN());


module Chess

using Printf

struct King end
struct Pawn end

function placepieces!(grid, ::King)
    axis = axes(grid, 1)
    while true
        r1, c1, r2, c2 = rand(axis, 4)
        if r1 != r2 && abs(r1 - r2) > 1 && abs(c1 - c2) > 1
            grid[r1, c1] = '♚'
            grid[r2, c2] = '♔'
            return grid
        end
    end
end

function placepieces!(grid, ch)
    axis = axes(grid, 1)
    while true
        r, c = rand(axis, 2)
        if grid[r, c] == ' '
            grid[r, c] = ch
            return grid
        end
    end
end

function placepieces!(grid, ch, ::Pawn)
    axis = axes(grid, 1)
    while true
        r, c = rand(axis, 2)
        if grid[r, c] == ' ' && r ∉ extrema(axis)
            grid[r, c] = ch
            return grid
        end
    end
end

function randposition!(grid)
    placepieces!(grid, King())
    foreach("♙♙♙♙♙♙♙♙♙♟♟♟♟♟♟♟♟") do ch
        placepieces!(grid, ch, Pawn())
    end
    foreach("♖♘♗♕♗♘♖♜♞♝♛♝♞♜") do ch
        placepieces!(grid, ch)
    end
    return grid
end

printgrid(grid) = println(join((join(grid[r, :], ' ') for r in 1:size(grid, 1)), '\n'))

end  # module Chess


// version 1.2.0

import java.util.Random
import kotlin.math.abs

val rand = Random()

val grid = List(8) { CharArray(8) }

const val NUL = '\u0000'

fun createFen(): String {
    placeKings()
    placePieces("PPPPPPPP", true)
    placePieces("pppppppp", true)
    placePieces("RNBQBNR", false)
    placePieces("rnbqbnr", false)
    return toFen()
}

fun placeKings() {
    while (true) {
        val r1 = rand.nextInt(8)
        val c1 = rand.nextInt(8)
        val r2 = rand.nextInt(8)
        val c2 = rand.nextInt(8)
        if (r1 != r2 && abs(r1 - r2) > 1 && abs(c1 - c2) > 1) {
            grid[r1][c1] = 'K'
            grid[r2][c2] = 'k'
            return
        }
    }
}

fun placePieces(pieces: String, isPawn: Boolean) {
    val numToPlace = rand.nextInt(pieces.length)
    for (n in 0 until numToPlace) {
        var r: Int
        var c: Int
        do {
            r = rand.nextInt(8)
            c = rand.nextInt(8)
        }
        while (grid[r][c] != NUL || (isPawn && (r == 7 || r == 0)))
        grid[r][c] = pieces[n]
    }
}

fun toFen(): String {
    val fen = StringBuilder()
    var countEmpty = 0
    for (r in 0..7) {
        for (c in 0..7) {
            val ch = grid[r][c]
            print ("%2c ".format(if (ch == NUL) '.' else ch))
            if (ch == NUL) {
                countEmpty++
            }
            else {
                if (countEmpty > 0) {
                    fen.append(countEmpty)
                    countEmpty = 0
                }
                fen.append(ch)
            }
        }
        if (countEmpty > 0) {
            fen.append(countEmpty)
            countEmpty = 0
        }
        fen.append("/")
        println()
    }
    return fen.append(" w - - 0 1").toString()
}

fun main(args: Array<String>) {
    println(createFen())
}


g = ConstantArray["", {8, 8}];
While[[email protected]@Differences[r = RandomChoice[Tuples[Range[8], 2], 2]] <= Sqrt[2], Null];
g = ReplacePart[g, {r[[1]] -> "K", r[[2]] -> "k"}];
avail = Position[g, "", {2}];
n = RandomInteger[{2, 14}];
rls = Thread[RandomSample[avail, n] -> RandomChoice[[email protected]"NBRQnbrq", n]];
g = ReplacePart[g, rls];
avail = RandomSample[DeleteCases[Position[g, "", {2}], {8, _}], RandomInteger[{2, 8}]];
g = ReplacePart[g, Thread[avail -> "P"]];
avail = RandomSample[DeleteCases[Position[g, "", {2}], {1, _}], RandomInteger[{2, 8}]];
g = ReplacePart[g, Thread[avail -> "p"]];
g //= Map[Split];
g = g /. (x : {"" ..}) :> ToString[Length[x]];
g //= Map[[email protected]*Flatten];
g = StringRiffle[Reverse[g], "/"];
g = g <> " w - - 0 1";
g


import random

type

  Piece {.pure.} = enum
    None
    WhiteBishop = ('B', "♗")
    WhiteKing = ('K', "♔")
    WhiteKnight = ('N', "♘")
    WhitePawn = ('P', "♙")
    WhiteQueen = ('Q', "♕")
    WhiteRook = ('R', "♖")
    BlackBishop = ('b', "♝")
    BlackKing = ('k', "♚")
    BlackKnight = ('n', "♞")
    BlackPawn = ('p', "♟")
    BlackQueen = ('q', "♛")
    BlackRook = ('r', "♜")

  Color {.pure.} = enum White, Black

  Grid = array[8, array[8, Piece]]

const
  # White pieces except king and pawns.
  WhitePieces = [WhiteQueen, WhiteRook, WhiteRook, WhiteBishop,
                 WhiteBishop, WhiteKnight, WhiteKnight]

  # Black pieces except king and pawns.
  BlackPieces = [BlackQueen, BlackRook, BlackRook, BlackBishop,
                 BlackBishop, BlackKnight, BlackKnight]

proc placeKings(grid: var Grid) =
  while true:
    let r1 = rand(7)
    let c1 = rand(7)
    let r2 = rand(7)
    let c2 = rand(7)
    if r1 != r2 and abs(r1 - r2) > 1 and abs(c1 - c2) > 1:
      grid[r1][c1] = WhiteKing
      grid[r2][c2] = BlackKing
      break

proc placePawns(grid: var Grid; color: Color) =
  let piece = if color == White: WhitePawn else: BlackPawn
  let numToPlace = rand(8)
  for n in 0..<numToPlace:
    var r, c: int
    while true:
      r = rand(7)
      c = rand(7)
      if grid[r][c] == None and r notin {0, 7}: break
    grid[r][c] = piece

proc placePieces(grid: var Grid; color: Color) =
  var pieces = if color == White: WhitePieces else: BlackPieces
  pieces.shuffle()
  let numToPlace = rand(7)
  for n in 0..<numToPlace:
    var r, c: int
    while true:
      r = rand(7)
      c = rand(7)
      if grid[r][c] == None: break
    grid[r][c] = pieces[n]

proc toFen(grid: Grid): string =
  var countEmpty = 0
  for r in 0..7:
    for c in 0..7:
      let piece = grid[r][c]
      if piece == None:
        stdout.write " . "
        inc countEmpty
      else:
        stdout.write ' ' & $piece & ' '
        if countEmpty > 0:
          result.add $countEmpty
          countEmpty = 0
        result.add chr(ord(piece))

    if countEmpty > 0:
      result.add $countEmpty
      countEmpty = 0

    result.add '/'
    echo ""

  result.add " w - - 0 1"

proc createFen(): string =
  var grid: Grid
  grid.placeKings()
  grid.placePawns(White)
  grid.placePawns(Black)
  grid.placePieces(White)
  grid.placePieces(Black)
  result = grid.toFen()

randomize()
echo createFen()


use strict;
use warnings;
use feature 'say';
use utf8;
use List::AllUtils <shuffle any natatime>;

sub pick1 { return @_[rand @_] }

sub gen_FEN {
    my $n = 1 + int rand 31;
    my @n = (shuffle(0 .. 63))[1 .. $n];

    my @kings;

  KINGS: {
    for my $a (@n) {
        for my $b (@n) {
            next unless $a != $b && abs(int($a/8) - int($b/8)) > 1 || abs($a%8 - $b%8) > 1;
            @kings = ($a, $b);
            last KINGS;
        }
        die 'No good place for kings!';
    }
    }

    my ($row, @pp);
    my @pieces = <p P n N b B r R q Q>;
    my @k      = rand() < .5 ? <K k> : <k K>;

    for my $sq (0 .. 63) {
        if (any { $_ == $sq } @kings) {
            push @pp, shift @k;
        }
        elsif (any { $_ == $sq } @n) {
            $row = 7 - int $sq / 8;
            push @pp,
                $row == 0 ? pick1(grep { $_ ne 'P' } @pieces)
              : $row == 7 ? pick1(grep { $_ ne 'P' } @pieces)
              :             pick1(@pieces);
        }
        else {
            push @pp, 'ø';
        }
    }

    my @qq;
    my $iter = natatime 8, @pp;
    while (my $row = join '', $iter->()) {
        $row =~ s/((ø)\2*)/length($1)/eg;
        push @qq, $row;
    }
    return join('/', @qq) . ' w - - 0 1';
}

say gen_FEN();


with javascript_semantics
constant show_bad_boards = false

string board

function fen()
    string res = ""
    for i=1 to 64 by 8 do
        integer empty = 0
        for j=i to i+7 do
            if board[j]='.' then
                empty += 1
            else
                if empty then
                    res &= empty+'0'
                    empty = 0
                end if
                res &= board[j]
            end if
        end for
        if empty then
            res &= empty+'0'
        end if
        if i<57 then res &= '/' end if
    end for
    res &= " w - - 0 1"
    return res
end function

function p15()
    string res = "pppppppprrnnbbq"
    -- promote 0..8 pawns
    for i=1 to rand(9)-1 do
        res[i] = res[rand(7)+8]
    end for
    res = shuffle(res)
    return res
end function

function kings_adjacent(sequence p12)
    integer {p1,p2} = sq_sub(p12,1),
            row_diff = abs(floor(p1/8)-floor(p2/8)),
            col_diff = abs(mod(p1,8)-mod(p2,8))
    return row_diff<=1 and col_diff<=1
end function

integer lp
procedure show_board()
    printf(1,"%d pieces\n%s",{lp,join_by(board,1,8,"")})
end procedure

while true do
    string pieces = "Kk"&                        -- kings
                    upper(p15())[1..rand(16)-1]& -- white
                    lower(p15())[1..rand(16)-1]  -- black
    lp = length(pieces)
    sequence p = tagset(64)
    p = shuffle(p)
    board = repeat('.',64)
    for i=1 to lp do board[p[i]] = pieces[i] end for

    if kings_adjacent(p[1..2]) then
        if show_bad_boards then show_board() end if
        puts(1,"kings adjacent - reshuffle\n\n")
    else
        -- check no pawn will be on a promotion square,
        -- and (above spec) no pawn has gone backwards:
        if find('p',lower(board[1..8]&board[57..64]))=0 then exit end if
        if show_bad_boards then show_board() end if
        puts(1,"pawn on rank 1/8 - reshuffle\n\n")
    end if
end while
show_board()
printf(1,"\n%s\n",{fen()})


(load "@lib/simul.l")
(seed (in "/dev/urandom" (rd 8)))
(de pieceN (P)
   (case P
      ("p" 8)
      ("q" 1)
      (T 2) ) )
(de pieceset ()
   (let C 0
      (make
         (for P (conc (cons "p") (shuffle '("r" "n" "b" "q")))
            (let (X (pieceN P)  N (rand 0 (+ X C)))
               (do N
                  (link P) )
               (if (= P "p")
                  (and
                     (> X N)
                     (inc 'C (- X N)) )
                  (and
                     (> N X)
                     (dec 'C (- N X)) ) ) ) ) ) ) )
(de neib (A)
   (let
      (X (/ (dec A) 8)
         Y (% (dec A) 8) )
      (filter
         '((N)
            (and
               (<= 1 N 64)
               (<=
                  (abs (- (/ (dec N) 8) X))
                  1 )
               (<=
                  (abs (- (% (dec N) 8) Y))
                  1 ) ) )
         (mapcar
            '((B) (+ B A))
            (-9 -8 -7 -1 1 7 8 9) ) ) ) )
(setq *B (need 64 "."))
(setq *P (conc (pieceset) (mapcar uppc (pieceset)) (cons "K")))
(for P *P
   (loop
      (T
         (=
            "."
            (car
               (setq @@
                  (nth
                     *B
                     (apply
                        rand
                        (if (or (= "p" P) (= "P" P))
                           (9 56)
                           (1 64) ) ) ) ) ) )
         (set @@ P) ) ) )
(loop
   (T
      (and
         (=
            "."
            (car
               (setq @@ (nth *B (setq @@@ (rand 1 64)))) ) )
         (fully
            '((N) (<> "K" (get *B N)))
            (neib @@@) ) )
      (set @@ "k") ) )
(setq *FEN
   (make
      (while *B
         (let (C 0  Lst (cut 8 '*B))
            (prinl Lst)
            (link
               (make
                  (for L Lst
                     (if (= L ".")
                        (inc 'C)
                        (and
                           (gt0 C)
                           (link (swap 'C 0)) )
                        (link L) ) )
                  (and
                     (gt0 C)
                     (link C) ) ) ) ) ) ) )
(println (pack (glue "/" *FEN) " w - - 0 1"))


import random

board = [[" " for x in range(8)] for y in range(8)]
piece_list = ["R", "N", "B", "Q", "P"]

def place_kings(brd):
	while True:
		rank_white, file_white, rank_black, file_black = random.randint(0,7), random.randint(0,7), random.randint(0,7), random.randint(0,7)
		diff_list = [abs(rank_white - rank_black),  abs(file_white - file_black)]
		if sum(diff_list) > 2 or set(diff_list) == set([0, 2]):
			brd[rank_white][file_white], brd[rank_black][file_black] = "K", "k"
			break

def populate_board(brd, wp, bp):
	for x in range(2):
		if x == 0:
			piece_amount = wp
			pieces = piece_list
		else:
			piece_amount = bp
			pieces = [s.lower() for s in piece_list]
		while piece_amount != 0:
			piece_rank, piece_file = random.randint(0, 7), random.randint(0, 7)
			piece = random.choice(pieces)
			if brd[piece_rank][piece_file] == " " and pawn_on_promotion_square(piece, piece_rank) == False:
				brd[piece_rank][piece_file] = piece
				piece_amount -= 1

def fen_from_board(brd):
	fen = ""
	for x in brd:
		n = 0
		for y in x:
			if y == " ":
				n += 1
			else:
				if n != 0:
					fen += str(n)
				fen += y
				n = 0
		if n != 0:
			fen += str(n)
		fen += "/" if fen.count("/") < 7 else ""
	fen += " w - - 0 1\n"
	return fen

def pawn_on_promotion_square(pc, pr):
	if pc == "P" and pr == 0:
		return True
	elif pc == "p" and pr == 7:
		return True
	return False

def start():
	piece_amount_white, piece_amount_black = random.randint(0, 15), random.randint(0, 15)
	place_kings(board)
	populate_board(board, piece_amount_white, piece_amount_black)
	print(fen_from_board(board))
	for x in board:
		print(x)

#entry point
start()


place_kings <- function(brd){
  ###
  #  Function that puts the two kings on the board
  #  and makes sure that they are not adjacent
  ###
  while (TRUE) {
    # generate positions for white and black kings
    rank_white <- sample(1:8, 1) ; file_white <- sample(1:8, 1)
    rank_black <- sample(1:8, 1) ; file_black <- sample(1:8, 1)
    # compute the differences between ranks and files
    diff_vec <- c(abs(rank_white - rank_black), abs(file_white - file_black))
    # if the two kings are not adjacent, place them on the board
    if (sum(diff_vec) > 2 | setequal(diff_vec, c(0,2))) {
      brd[rank_white, file_white] <- "K"
      brd[rank_black, file_black] <- "k"
      break
    }
  }
  return(brd)
}

pawn_on_extreme_ranks <- function(pc, pr){
  ###
  #  Function that checks whether a pawn is on the first or eight rank
  #  (such a situation is not possible in chess)
  ###
  if (pc %in% c("P","p") & pr %in% c(1,8))
    return(TRUE)
  else
    return(FALSE)
}

populate_board <- function(brd, wp, bp){
  ###
  #  Function that puts pieces on the board making sure that they
  #  are not on the same squares, and verifying for pawn_on_extreme_ranks
  ###
  # initialization
  piece_list <- c("P", "N", "B", "R", "Q")
  for (color in c("white", "black")){
    # iterate for white (first) and black (after) pieces
    if (color == "white"){
      n_pieces = wp
      pieces = piece_list
    }
    else {
      n_pieces = bp
      pieces = tolower(piece_list)
    }
    # place pieces one by one until we have them
    while (n_pieces != 0){
      piece_rank <- sample(1:8, 1) ; piece_file <- sample(1:8, 1)
      piece <- sample(pieces, 1)
      # check if square is empty and it is not a pawn on an extreme rank
      if (brd[piece_rank, piece_file] == " " & !pawn_on_extreme_ranks(piece, piece_rank)){
        brd[piece_rank, piece_file] <- piece
        n_pieces <- n_pieces - 1
      }
    }
  }
  return(brd)
}

fen_from_board <- function(brd){
  ###
  #  Function that prints out the FEN of a given input board
  ###
  # create vector of positions by row
  fen <- apply(brd, 1, function(x) {
    r <- rle(x)
    paste(ifelse(r$values == " ", r$lengths, r$values), collapse = "")
    })
  # paste them together with separator '/' and add the final string
  fen <- paste(paste(fen, collapse = "/"), "w - - 0 1")
  return(fen)
}

generate_fen <- function(){
  ###
  #  This function calls all the functions above and generates
  #  the board representation along with its FEN
  ###
  # initialization
  board <- matrix(" ", nrow = 8, ncol = 8)
  # generate random amount of white and black pieces (kings excluded)
  n_pieces_white <- sample(0:31, 1) ; n_pieces_black <- sample(0:31, 1)
  # place kings on board
  board <- place_kings(board)
  # put other pieces on board
  board <- populate_board(board, wp = n_pieces_white, bp = n_pieces_black)
  # print board and FEN
  print(board)
  cat("\n")
  cat(fen_from_board(board))
}

generate_fen()


sub pick-FEN {
    # First we chose how many pieces to place
    my $n = (2..32).pick;

    # Then we pick $n squares
    my @n = (^64).pick($n);

    # We try to find suitable king positions on non-adjacent squares.
    # If we could not find any, we return recursively
    return pick-FEN() unless
    my @kings[2] = first -> [$a, $b] {
        $a !== $b && abs($a div 8 - $b div 8) | abs($a mod 8 - $b mod 8) > 1
    }, (@n X @n);

    # We make a list of pieces we can pick (apart from the kings)
    my @pieces = <p P n N b B r R q Q>;

    # We make a list of two king symbols to pick randomly a black or white king
    my @k = <K k>.pick(*);

    return (gather for ^64 -> $sq {
        if $sq == @kings.any { take @k.shift }
        elsif $sq == @n.any {
            my $row = 7 - $sq div 8;
            take
            $row == 7 ?? @pieces.grep(none('P')).pick !!
            $row == 0 ?? @pieces.grep(none('p')).pick !!
            @pieces.pick;
        }
        else { take 'ø' }
    }).rotor(8)».join».subst(/ø+/,{ .chars }, :g).join('/') ~ ' w - - 0 1';
}

say pick-FEN();


L(fname) fs:list_dir(‘.’)
   I fname.ends_with(‘.txt’)
      V fcontents = File(fname).read()
      File(fname, ‘w’).write(fcontents.replace(‘Goodbye London!’, ‘Hello, New York!’))


/*REXX program generates a  chess position (random pieces & positions)  in a FEN format.*/
parse arg seed CBs .                             /*obtain optional arguments from the CL*/
if datatype(seed,'W')  then call random ,,seed   /*SEED given for RANDOM repeatability? */
if CBs=='' | CBs==","  then CBs=1                /*CBs:  number of generated ChessBoards*/
                                                 /* [↓]  maybe display any # of boards. */
      do boards=1  for abs(CBs)                  /* [↓]  maybe display separator & title*/
      if sign(CBs)\==CBs  then do;   say;   say center(' board' boards" ", 79, '▒');   end
      @.=.; !.[email protected].                                /*initialize the chessboard to be empty*/
                  do p=1  for random(2, 32)      /*generate a random number of chessmen.*/
                  if p<3  then call piece 'k'    /*a   king   of each color.            */
                          else call piece substr('bnpqr', random(1, 5), 1)
                  end  /*p*/                     /* [↑]  place a piece on the chessboard*/
      call cb                                    /*display the ChessBoard  and  its FEN.*/
      end          /*boards*/                    /* [↑]  CB ≡  ─    ─                   */
exit                                             /*stick a fork in it,  we're all done. */
/*──────────────────────────────────────────────────────────────────────────────────────*/
cb: fen=;  do   r=8  for 8  by -1;  $=                       /*the board rank  (so far).*/
             do f=8  for 8  by -1;  $= $  ||  @.r.f          /*append the board file.   */
             end   /*f*/
           say $                                             /*display the board rank.  */
             do e=8  for 8  by -1;  $= changestr( copies(., e),  $, e)    /* . ≡ filler.*/
             end   /*e*/
           fen= fen  ||  $  ||  left('/', r\==1)             /*append / if not 1st rank.*/
           end     /*r*/                                     /* [↑]  append $ str to FEN*/
    say                                                      /*display a blank sep. line*/
    say 'FEN='fen   "w - - 0 1"                              /*Forsyth─Edwards Notation.*/
    return                                                   /* [↑]  display chessboard.*/
/*──────────────────────────────────────────────────────────────────────────────────────*/
piece: parse arg x;    if p//2  then upper x;   arg ux           /*use white if  odd  P.*/
       if CBs<0 & p>2  then if random(1)  then upper x           /*CBs>0?  Use balanced.*/
                                                                 /*[↓]  # isn't changed.*/
         do #=0  by 0;  r= random(1, 8);   f= random(1, 8)       /*random rank and file.*/
         if @.r.f\==.   then iterate                             /*is position occupied?*/
         if (x=='p'  & r==1)  |  (x=="P"  & r==8)  then iterate  /*any promoting pawn?  */
                                                                 /*[↑]  skip these pawns*/
         if ux=='K'  then do    rr=r-1 for 3                     /*[↓]  neighbor ≡ king?*/
                             do ff=f-1 for 3;  if !.rr.ff=='K'  then iterate #   /*king?*/
                             end   /*rr*/                        /*[↑]  neighbor ≡ king?*/
                          end      /*ff*/                        /*[↑]  we're all done. */
         @.r.f=  x                                               /*put random piece.    */
         !.r.f= ux;  return                                      /* "     "     "  upper*/
         end   /*#*/                                             /*#: isn't incremented.*/


with Ada.Strings.Unbounded, Ada.Text_IO, Ada.Command_Line, Ada.Directories;

procedure Global_Replace is

   subtype U_String is Ada.Strings.Unbounded.Unbounded_String;
   function "+"(S: String) return U_String renames
     Ada.Strings.Unbounded.To_Unbounded_String;
   function "-"(U: U_String) return String renames
     Ada.Strings.Unbounded.To_String;

   procedure String_Replace(S: in out U_String; Pattern, Replacement: String) is
      -- example: if S is "Mary had a XX lamb", then String_Replace(S, "X", "little");
      --          will turn S into "Mary had a littlelittle lamb"
      --          and String_Replace(S, "Y", "small"); will not change S

      Index : Natural;
   begin
      loop
         Index := Ada.Strings.Unbounded.Index(Source => S, Pattern => Pattern);
         exit when Index = 0;
         Ada.Strings.Unbounded.Replace_Slice
           (Source => S, Low => Index, High => Index+Pattern'Length-1,
            By => Replacement);
      end loop;
   end String_Replace;

   procedure File_Replace(Filename: String; Pattern, Replacement: String) is
      -- applies String_Rplace to each line in the file with the given Filename
      -- propagates any exceptions, when, e.g., the file does not exist

      I_File, O_File: Ada.Text_IO.File_Type;
      Line: U_String;
      Tmp_Name: String := Filename & ".tmp";
         -- name of temporary file; if that file already exists, it will be overwritten
   begin
      Ada.Text_IO.Open(I_File, Ada.Text_IO.In_File, Filename);
      Ada.Text_IO.Create(O_File, Ada.Text_IO.Out_File, Tmp_Name);
      while not Ada.Text_IO.End_Of_File(I_File) loop
         Line := +Ada.Text_IO.Get_Line(I_File);
         String_Replace(Line, Pattern, Replacement);
         Ada.Text_IO.Put_Line(O_File, -Line);
      end loop;
      Ada.Text_IO.Close(I_File);
      Ada.Text_IO.Close(O_File);
      Ada.Directories.Delete_File(Filename);
      Ada.Directories.Rename(Old_Name => Tmp_Name, New_Name => Filename);
   end File_Replace;

   Pattern:     String := Ada.Command_Line.Argument(1);
   Replacement: String :=  Ada.Command_Line.Argument(2);

begin
   Ada.Text_IO.Put_Line("Replacing """ & Pattern
                          & """ by """ & Replacement & """ in"
                          & Integer'Image(Ada.Command_Line.Argument_Count - 2)
                          & " files.");
   for I in 3 .. Ada.Command_Line.Argument_Count loop
      File_Replace(Ada.Command_Line.Argument(I), Pattern, Replacement);
   end loop;
end Global_Replace;


SetWorkingDir %A_ScriptDir%      ; Change the working directory to the script's location
listFiles := "a.txt|b.txt|c.txt" ; Define a list of files in the current working directory
loop, Parse, listFiles, |
{
	; The above parses the list based on the | character
	fileread, contents, %A_LoopField% ; Read the file
	fileDelete, %A_LoopField%         ; Delete the file
	stringReplace, contents, contents, Goodbye London!, Hello New York!, All ; replace all occurrences
	fileAppend, %contents%, %A_LoopField% ; Re-create the file with new contents
}


def hasNK( board, a, b )
    for g in -1 .. 1
        for f in -1 .. 1
            aa = a + f; bb = b + g
            if aa.between?( 0, 7 ) && bb.between?( 0, 7 )
                p = board[aa + 8 * bb]
                if p == "K" || p == "k"; return true; end
            end
        end
    end
    return false
end
def generateBoard(  board, pieces  )
    while( pieces.length > 1 )
        p = pieces[pieces.length - 1]
        pieces = pieces[0...-1]
        while( true )
            a = rand( 8 ); b = rand( 8 )
            if ( ( b == 0 || b == 7 ) && ( p == "P" || p == "p" ) ) ||
               ( ( p == "k" || p == "K" ) && hasNK( board, a, b ) ); next; end
            if board[a + b * 8] == nil; break;end
        end
        board[a + b * 8] = p
    end
end
pieces = "ppppppppkqrrbbnnPPPPPPPPKQRRBBNN"
for i in 0 .. 10
    e = pieces.length - 1
    while e > 0
        p = rand( e ); t = pieces[e];
        pieces[e] = pieces[p]; pieces[p] = t; e -= 1
    end
end
board = Array.new( 64 ); generateBoard( board, pieces )
puts
e = 0
for j in 0 .. 7
    for i in 0 .. 7
        if board[i + 8 * j] == nil; e += 1
        else
            if e > 0; print( e ); e = 0; end
            print( board[i + 8 * j] )
        end
    end
    if e > 0; print( e ); e = 0; end
    if j < 7; print( "/" ); end
end
print( " w - - 0 1\n" )
for j in 0 .. 7
    for i in 0 .. 7
        if board[i + j * 8] == nil; print( "." )
        else print( board[i + j * 8] ); end
    end
    puts
end


# syntax: GAWK -f GLOBALLY_REPLACE_TEXT_IN_SEVERAL_FILES.AWK filename(s)
BEGIN {
    old_text = "Goodbye London!"
    new_text = "Hello New York!"
}
BEGINFILE {
    nfiles_in++
    text_found = 0
    delete arr
}
{   if (gsub(old_text,new_text,$0) > 0) {
      text_found++
    }
    arr[FNR] = $0
}
ENDFILE {
    if (text_found > 0) {
      nfiles_out++
      close(FILENAME)
      for (i=1; i<=FNR; i++) {
        printf("%s\n",arr[i]) >FILENAME
      }
    }
}
END {
    printf("files: %d read, %d updated\n",nfiles_in,nfiles_out)
    exit(0)
}


CONST matchtext = "Goodbye London!"
CONST repltext  = "Hello New York!"
CONST matchlen  = LEN(matchtext)

DIM L0 AS INTEGER, x AS INTEGER, filespec AS STRING, linein AS STRING

L0 = 1
WHILE LEN(COMMAND$(L0))
    filespec = DIR$(COMMAND$(L0))
    WHILE LEN(filespec)
        OPEN filespec FOR BINARY AS 1
            linein = SPACE$(LOF(1))
            GET #1, 1, linein
            DO
                x = INSTR(linein, matchtext)
                IF x THEN
                    linein = LEFT$(linein, x - 1) & repltext & MID$(linein, x + matchlen)
                    ' If matchtext and repltext are of equal length (as in this example)
                    ' then you can replace the above line with this:
                    ' MID$(linein, x) = repltext
                    ' This is somewhat more efficient than having to rebuild the string.
                ELSE
                    EXIT DO
                END IF
            LOOP
        ' If matchtext and repltext are of equal length (as in this example), or repltext
        ' is longer than matchtext, you could just write back to the file while it's open
        ' in BINARY mode, like so:
        ' PUT #1, 1, linein
        ' But since there's no way to reduce the file size via BINARY and PUT, we do this:
        CLOSE
        OPEN filespec FOR OUTPUT AS 1
            PRINT #1, linein;
        CLOSE
        filespec = DIR$
    WEND
    L0 += 1
WEND


use std::fmt::Write;

use rand::{Rng, distributions::{Distribution, Standard}};

const EMPTY: u8 = b'.';

#[derive(Clone, Debug)]
struct Board {
    grid: [[u8; 8]; 8],
}

impl Distribution<Board> for Standard {
    fn sample<R: Rng + ?Sized>(&self, rng: &mut R) -> Board {
        let mut board = Board::empty();
        board.place_kings(rng);
        board.place_pieces(rng, b"PPPPPPPP", true);
        board.place_pieces(rng, b"pppppppp", true);
        board.place_pieces(rng, b"RNBQBNR", false);
        board.place_pieces(rng, b"rnbqbnr", false);
        board
    }
}

impl Board {
    fn empty() -> Self {
        Board { grid: [[EMPTY; 8]; 8] }
    }

    fn fen(&self) -> String {
        let mut fen = String::new();
        let mut count_empty = 0;
        for row in &self.grid {
            for &ch in row {
                print!("{} ", ch as char);
                if ch == EMPTY {
                    count_empty += 1;
                } else {
                    if count_empty > 0 {
                        write!(fen, "{}", count_empty).unwrap();
                        count_empty = 0;
                    }
                    fen.push(ch as char);
                }
            }
            if count_empty > 0 {
                write!(fen, "{}", count_empty).unwrap();
                count_empty = 0;
            }
            fen.push('/');
            println!();
        }
        fen.push_str(" w - - 0 1");
        fen
    }

    fn place_kings<R: Rng + ?Sized>(&mut self, rng: &mut R) {
        loop {
            let r1: i8 = rng.gen_range(0, 8);
            let c1: i8 = rng.gen_range(0, 8);
            let r2: i8 = rng.gen_range(0, 8);
            let c2: i8 = rng.gen_range(0, 8);
            if r1 != r2 && (r1 - r2).abs() > 1 && (c1 - c2).abs() > 1 {
                self.grid[r1 as usize][c1 as usize] = b'K';
                self.grid[r2 as usize][c2 as usize] = b'k';
                return;
            }
        }
    }

    fn place_pieces<R: Rng + ?Sized>(&mut self, rng: &mut R, pieces: &[u8], is_pawn: bool) {
        let num_to_place = rng.gen_range(0, pieces.len());
        for &piece in pieces.iter().take(num_to_place) {
            let mut r = rng.gen_range(0, 8);
            let mut c = rng.gen_range(0, 8);
            while self.grid[r][c] != EMPTY || (is_pawn && (r == 7 || r == 0)) {
                r = rng.gen_range(0, 8);
                c = rng.gen_range(0, 8);
            }
            self.grid[r][c] = piece;
        }
    }
}

fn main() {
    let b: Board = rand::random();
    println!("{}", b.fen());
}


import scala.math.abs
import scala.util.Random

object RandomFen extends App {
  val rand = new Random

  private def createFen = {
    val grid = Array.ofDim[Char](8, 8)

    def placeKings(grid: Array[Array[Char]]): Unit = {
      var r1, c1, r2, c2 = 0
      do {
        r1 = rand.nextInt(8)
        c1 = rand.nextInt(8)
        r2 = rand.nextInt(8)
        c2 = rand.nextInt(8)
      } while (r1 == r2 || abs(r1 - r2) <= 1 || abs(c1 - c2) <= 1)
      grid(r1)(c1) = 'K'
      grid(r2)(c2) = 'k'
    }

    def placePieces(grid: Array[Array[Char]],
                    pieces: String,
                    isPawn: Boolean): Unit = {
      val numToPlace = rand.nextInt(pieces.length)

      for (n <- 0 until numToPlace) {
        var r, c = 0
        do {
          r = rand.nextInt(8)
          c = rand.nextInt(8)
        } while (grid(r)(c) != 0 || (isPawn && (r == 7 || r == 0)))
        grid(r)(c) = pieces(n)
      }
    }

    def toFen(grid: Array[Array[Char]]) = {
      val fen = new StringBuilder
      var countEmpty = 0
      for (r <- grid.indices) {
        for (c <- grid.indices) {
          val ch = grid(r)(c)
          print(f"${if (ch == 0) '.' else ch}%2c ")
          if (ch == 0) countEmpty += 1
          else {
            if (countEmpty > 0) {
              fen.append(countEmpty)
              countEmpty = 0
            }
            fen.append(ch)
          }
        }
        if (countEmpty > 0) {
          fen.append(countEmpty)
          countEmpty = 0
        }
        fen.append("/")
        println()
      }
      fen.append(" w - - 0 1").toString
    }

    placeKings(grid)
    placePieces(grid, "PPPPPPPP", isPawn = true)
    placePieces(grid, "pppppppp", isPawn = true)
    placePieces(grid, "RNBQBNR", isPawn = false)
    placePieces(grid, "rnbqbnr", isPawn = false)
    toFen(grid)
  }

  println(createFen)

}


      FindThis$ = "Goodbye London!"
      ReplaceWith$ = "Hello New York!"

      DIM Files$(3)
      Files$() = "C:\test1.txt", "C:\test2.txt", "C:\test3.txt", "C:\test4.txt"

      FOR f% = 0 TO DIM(Files$(),1)
        infile$ = Files$(f%)
        infile% = OPENIN(infile$)
        IF infile%=0 ERROR 100, "Failed to open file " + infile$
        tmpfile$ = @tmp$+"replace.txt"
        tmpfile% = OPENOUT(tmpfile$)

        WHILE NOT EOF#infile%
          INPUT #infile%, a$
          IF ASCa$=10 a$ = MID$(a$,2)
          l% = LEN(FindThis$)
          REPEAT
            here% = INSTR(a$, FindThis$)
            IF here% a$ = LEFT$(a$,here%-1) + ReplaceWith$ + MID$(a$,here%+l%)
          UNTIL here% = 0
          PRINT #tmpfile%, a$ : BPUT #tmpfile%,10
        ENDWHILE
        CLOSE #infile%
        CLOSE #tmpfile%

        OSCLI "DEL """ + infile$ + """"
        OSCLI "REN """ + tmpfile$ + """ """ + infile$ + """"
      NEXT
      END


#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; /* no match found, don't change file */

	ftruncate(fd, 0);
	lseek(fd, 0, 0);
	do {
		write(fd, start, end - start);	/* write content before match */
		write(fd, to, nlen);		/* write replacement of match */
		start = end + len;		/* skip to end of match */
						/* find match again */
		end = find_match(start, buf + st.st_size, from, len);
	} while (end);

	/* write leftover after last match */
	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;
}


class Fen {

    public createFen() {
        let grid: string[][];

        grid = [];

        for (let r = 0; r < 8; r++) {
            grid[r] = [];
            for (let c = 0; c < 8; c++) {
                grid[r][c] = "0";
            }
        }

        this.placeKings(grid);
        this.placePieces(grid, "PPPPPPPP", true);
        this.placePieces(grid, "pppppppp", true);
        this.placePieces(grid, "RNBQBNR", false);
        this.placePieces(grid, "rnbqbnr", false);
        return this.toFen(grid);
    }

    private placeKings(grid: string[][]): void {
        let r1, c1, r2, c2: number;
        while (true) {
            r1 = Math.floor(Math.random() * 8);
            c1 = Math.floor(Math.random() * 8);
            r2 = Math.floor(Math.random() * 8);
            c2 = Math.floor(Math.random() * 8);
            if (r1 != r2 && Math.abs(r1 - r2) > 1 && Math.abs(c1 - c2) > 1) {
                break;
            }
        }
        grid[r1][c1] = "K";
        grid[r2][c2] = "k";
    }

    private placePieces(grid: string[][], pieces: string, isPawn: boolean): void {
        let numToPlace: number = Math.floor(Math.random() * pieces.length);
        for (let n = 0; n < numToPlace; n++) {
            let r, c: number;
            do {
                r = Math.floor(Math.random() * 8);
                c = Math.floor(Math.random() * 8);
            } while (grid[r][c] != "0" || (isPawn && (r == 7 || r == 0)));

            grid[r][c] = pieces.charAt(n);
        }
    }

    private toFen(grid: string[][]): string {
        let result: string = "";
        let countEmpty: number = 0;
        for (let r = 0; r < 8; r++) {
            for (let c = 0; c < 8; c++) {
                let char: string = grid[r][c];
                if (char == "0") {
                    countEmpty++;
                } else {
                    if (countEmpty > 0) {
                        result += countEmpty;
                        countEmpty = 0;
                    }
                    result += char;
                }
            }
            if (countEmpty > 0) {
                result += countEmpty;
                countEmpty = 0;
            }
            result += "/";
        }
        return result += " w - - 0 1";
    }

}

let fen: Fen = new Fen();
console.log(fen.createFen());


import "random" for Random
import "/fmt" for Fmt

var rand = Random.new()

var grid = List.filled(8, null)
for (i in 0..7) grid[i] = List.filled(9, ".")

var placeKings = Fn.new {
    while (true) {
        var r1 = rand.int(8)
        var c1 = rand.int(8)
        var r2 = rand.int(8)
        var c2 = rand.int(8)
        if (r1 != r2 && (r1 - r2).abs > 1 && (c1 - c2).abs > 1) {
            grid[r1][c1] = "K"
            grid[r2][c2] = "k"
            return
        }
    }
}

var placePieces = Fn.new { |pieces, isPawn|
    var numToPlace = rand.int(pieces.count)
    for (n in 0...numToPlace) {
        var r
        var c
        while (true) {
            r = rand.int(8)
            c = rand.int(8)
            if (grid[r][c] == "." && !(isPawn && (r == 7 || r == 0))) break
        }
        grid[r][c] = pieces[n]
    }
}

var toFen = Fn.new {
    var fen = ""
    var countEmpty = 0
    for (r in 0..7) {
        for (c in 0..7) {
            var ch = grid[r][c]
            Fmt.write("$2s ", ch)
            if (ch == ".") {
                countEmpty = countEmpty + 1
            } else {
                if (countEmpty > 0) {
                    fen = fen + countEmpty.toString
                    countEmpty = 0
                }
                fen = fen + ch
            }
        }
        if (countEmpty > 0) {
            fen = fen + countEmpty.toString
            countEmpty = 0
        }
        fen = fen + "/"
        System.print()
    }
    return fen + " w - - 0 1"
}

var createFen = Fn.new {
    placeKings.call()
    placePieces.call("PPPPPPPP", true)
    placePieces.call("pppppppp", true)
    placePieces.call("RNBQBNR", false)
    placePieces.call("rnbqbnr", false)
    return toFen.call()
}

System.print(createFen.call())


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!"));
        }
    }
}


#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 ;
}


dim grid(8, 8)

sub placeKings()
    local r1, r2, c1, c2

    do
        r1 = int(ran(8))
        c1 = int(ran(8))
        r2 = int(ran(8))
        c2 = int(ran(8))
        if (r1 <> r2 and abs(r1 - r2) > 1 and abs(c1 - c2) > 1) then
            grid(r1, c1) = asc("K")
            grid(r2, c2) = asc("k")
            return
        end if
    loop
end sub

sub placePieces(pieces$, isPawn)
    local n, r, c, numToPlace

    numToPlace = int(ran(len(pieces$)))
    for n = 0 to numToPlace-1
        repeat
            r = int(ran(8))
            c = int(ran(8))
        until(not(grid(r, c) or (isPawn and (r = 7 or r = 0))))
        grid(r, c) = asc(mid$(pieces$, n, 1))
    next
end sub

sub toFen()
    local fen$, ch, r, c, countEmpty

    for r = 0 to 8-1
        for c = 0 to 8-1
            ch = grid(r, c)
            if ch then print chr$(ch); else print "."; end if
            if not ch then
                countEmpty = countEmpty + 1
            else
                if countEmpty then
                    fen$ = fen$ + chr$(countEmpty + 48)
                    countEmpty = 0
                end if
                fen$ = fen$ + chr$(ch)
            end if
        next
        if countEmpty then
            fen$ = fen$ + chr$(countEmpty + 48)
            countEmpty = 0
        end if
        fen$ = fen$ + "/"
        print
    next
    fen$ = fen$ + " w - - 0 1"
    print fen$
end sub

sub createFen()
    placeKings()
    placePieces("PPPPPPPP", TRUE)
    placePieces("pppppppp", TRUE)
    placePieces("RNBQBNR", FALSE)
    placePieces("rnbqbnr", FALSE)
    toFen()
end sub

createFen()


fcn pickFEN{
   # First we chose how many pieces to place: 2 to 32
   n := (0).random(2,33);

   # Then we pick $n squares: first n of shuffle (0,1,2,3...63)
   n = [0..63].walk().shuffle()[0,n];

   # We try to find suitable king positions on non-adjacent squares.
   # If we could not find any, we return recursively
   kings := Walker.cproduct(n,n).filter1(fcn([(a,b)]){  // Cartesian product
      a!=b and (a/8 - b/8).abs() or (a%8 - b%8).abs()>1
   }); # (a,b) on success, False on fail
   if(not kings) return(pickFEN());    // tail recursion

   # We make a list of pieces we can pick (apart from the kings)
   pieces,pnp,pnP := "p P n N b B r R q Q".split(" "), pieces-"p", pieces-"P";

   # We make a list of two king symbols to pick randomly a black or white king
   k := "K k".split(" ").shuffle();

   [0..63].apply('wrap(sq){  # look at each square
      if(kings.holds(sq)) k.pop();
      else if(n.holds(sq)){
         row,n,n2 := 7 - sq/8, (0).random(pieces.len()), (0).random(pnp.len());
	 if(     row == 7) pnP[n2]  // no white pawn in the promotion square
	 else if(row == 0) pnp[n2]  // no black pawn in the promotion square
	 else 		   pieces[n] // otherwise, any ole random piece
      }
      else "#"  // empty square
   })
   .pump(List,T(Void.Read,7),"".append,subst)  // chunkize into groups of 8 chars (1 row)
   .concat("/") + " w - - 0 1"
}
fcn subst(str){  // replace "#" with count of #s
   re :=RegExp("#+");
   while(re.search(str,1)){ n,m:=re.matched[0]; str=String(str[0,n],m,str[n+m,*]) }
   str
}


(defn hello-goodbye [& more]
  (doseq [file more]
    (spit file (.replace (slurp file) "Goodbye London!" "Hello New York!"))))


(defun hello-goodbye (files)
  (labels ((replace-from-file (file)
             (with-open-file (in file)
               (loop for line = (read-line in nil)
                  while line do
                    (loop for index = (search "Goodbye London!" line)
                       while index do
                         (setf (subseq line index) "Hello New York!"))
                  collecting line)))
           (write-lines-to-file (lines file)
             (with-open-file (out file :direction :output :if-exists :overwrite)
               (dolist (line lines)
                 (write-line line out))))
           (replace-in-file (file)
             (write-lines-to-file (replace-from-file file) file)))
    (map nil #'replace-in-file files)))


import std.file, std.array;

void main() {
    auto from = "Goodbye London!", to = "Hello, New York!";
    foreach (fn; "a.txt b.txt c.txt".split()) {
        write(fn, replace(cast(string)read(fn), from, to));
    }
}


program Globally_replace_text_in_several_files;

{$APPTYPE CONSOLE}

uses
  System.SysUtils,
  System.IoUtils;

procedure StringReplaceByFile(_old, _new: string; FileName: TFilename;
  ReplaceFlags: TReplaceFlags = []); overload
var
  Text: string;
begin
  if not FileExists(FileName) then
    exit;
  Text := TFile.ReadAllText(FileName);
  TFile.Delete(FileName);
  TFile.WriteAllText(StringReplace(Text, _old, _new, ReplaceFlags), FileName);
end;

procedure StringReplaceByFile(_old, _new: string; FileNames: TArray<TFileName>;
  ReplaceFlags: TReplaceFlags = []); overload;
begin
  for var fn in FileNames do
    StringReplaceByFile(_old, _new, fn);
end;

begin
  StringReplaceByFile('Goodbye London!', 'Hello New York!', ['a.txt', 'b.txt', 'c.txt']);
end.


-module( globally_replace_text ).

-export( [in_files/3, main/1] ).

in_files( Old, New, Files ) when is_list(Old) ->
        in_files( binary:list_to_bin(Old), binary:list_to_bin(New), Files );
in_files( Old, New, Files ) -> [replace_in_file(Old, New, X, file:read_file(X)) || X <- Files].

main( [Old, New | Files] ) -> in_files( Old, New, Files ).

replace_in_file( Old, New, File, {ok, Binary} ) ->
	replace_in_file_return( File, file:write_file(File, binary:replace(Binary, Old, New, [global])) );
replace_in_file( _Old, _New, File, {error, Error} ) ->
        io:fwrite( "Error: Could not read ~p: ~p~n", [File, Error] ),
        error.

replace_in_file_return( _File, ok ) -> ok;
replace_in_file_return( File, {error, Error} ) ->
	io:fwrite( "Error: Could not write ~p: ~p~n", [File, Error] ),
        error.


open System.IO

[<EntryPoint>]
let main args =
    let textFrom = "Goodbye London!"
    let textTo = "Hello New York!"
    for name in args do
        let content = File.ReadAllText(name)
        let newContent = content.Replace(textFrom, textTo)
        if content <> newContent then
            File.WriteAllText(name, newContent)
    0


USING: fry io.encodings.utf8 io.files kernel qw sequences
splitting ;

: global-replace ( files old new -- )
    '[
        [ utf8 file-contents _ _ replace ]
        [ utf8 set-file-contents ] bi
    ] each ;

qw{ a.txt b.txt c.txt }
"Goodbye London!" "Hello New York!" global-replace


      SUBROUTINE FILEHACK(FNAME,THIS,THAT)	!Attacks a file!
       CHARACTER*(*) FNAME	!The name of the file, presumed to contain text.
       CHARACTER*(*) THIS	!The text sought in each record.
       CHARACTER*(*) THAT	!Its replacement, should it be found.
       INTEGER F,T		!Mnemonics for file unit numbers.
       PARAMETER (F=66,T=67)	!These should do.
       INTEGER L		!A length
       CHARACTER*6666 ALINE	!Surely sufficient?
       LOGICAL AHIT		!Could count them, but no report is called for.
        INQUIRE(FILE = FNAME, EXIST = AHIT)	!This mishap is frequent, so attend to it.
        IF (.NOT.AHIT) RETURN			!Nothing can be done!
        OPEN (F,FILE=FNAME,STATUS="OLD",ACTION="READWRITE")	!Grab the source file.
        OPEN (T,STATUS="SCRATCH")	!Request a temporary file.
        AHIT = .FALSE.		!None found so far.
Chew through the input, replacing THIS by THAT while writing to the temporary file..
   10   READ (F,11,END = 20) L,ALINE(1:MIN(L,LEN(ALINE)))	!Grab a record.
        IF (L.GT.LEN(ALINE)) STOP "Monster record!"		!Perhaps unmanageable.
   11   FORMAT (Q,A)		!Obviously, Q = length of characters unread in the record.
        L1 = 1			!Start at the start.
   12   L2 = INDEX(ALINE(L1:L),THIS)	!Look from L1 onwards.
        IF (L2.LE.0) THEN		!A hit?
          WRITE (T,13) ALINE(L1:L)	!No. Finish with the remainder of the line.
   13     FORMAT (A)			!Thus finishing the output line.
          GO TO 10			!And try for the next record.
        END IF				!So much for not finding THIS.
   14   L2 = L1 + L2 - 2	!Otherwise, THIS is found, starting at L1.
        WRITE (T,15) ALINE(L1:L2)	!So roll the text up to the match, possibly none.
   15   FORMAT (A,$)			!But not ending the record.
        WRITE (T,15) THAT		!Because THIS is replaced by THAT.
        AHIT = .TRUE.			!And we've found at least one match.
        L1 = L2 + LEN(THIS) + 1		!Finger the first character beyond the matching THIS.
        IF (L - L1 + 1 .GE. LEN(THIS)) GO TO 12	!Might another search succeed?
        WRITE (T,13) ALINE(L1:L)	!Nope. Finish the line with the tail end.
        GO TO 10		!And try for another record.
Copy the temporary file back over the source file. Hope for no mishap and data loss!
   20   IF (AHIT) THEN	!If there were no hits, there is nothing to do.
          CLOSE (F)		!Oh well.
          REWIND T		!Go back to the start.
          OPEN (F,FILE="new"//FNAME,STATUS = "REPLACE",ACTION = "WRITE")	!Overwrite...
   21     READ (T,11,END = 22) L,ALINE(1:MIN(L,LEN(ALINE)))	!Grab a line.
          IF (L.GT.LEN(ALINE)) STOP "Monster changed record!"	!Once you start checking...
          WRITE (F,13) ALINE(1:L) 		!In case LEN(THAT) > LEN(THIS)
          GO TO 21			!Go grab the next line.
        END IF		!So much for the replacement of the file.
   22   CLOSE(T)	!Finished: it will vanish.
        CLOSE(F)	!Hopefully, the buffers will be written.
      END	!So much for that.

      PROGRAM ATTACK
      INTEGER N
      PARAMETER (N = 6)		!More than one, anyway.
      CHARACTER*48 VICTIM(N)	!Alternatively, the file names could be read from a file
      DATA VICTIM/		!Along with the target and replacement texts in each case.
     1 "StaffStory.txt",
     2 "Accounts.dat",
     3 "TravelAgent.txt",
     4 "RemovalFirm.dat",
     5 "Addresses.txt",
     6 "SongLyrics.txt"/	!Invention flags.

      DO I = 1,N	!So, step through the list.
        CALL FILEHACK(VICTIM(I),"Goodbye London!","Hello New York!")	!One by one.
      END DO		!On to the next.

      END


Const matchtext = "Goodbye London!"
Const repltext  = "Hello New York!"
Const matchlen  = Len(matchtext)

Dim As Integer x, L0 = 1
dim as string filespec, linein

L0 = 1
While Len(Command(L0))
    filespec = Dir(Command(L0))
    While Len(filespec)
        Open filespec For Binary As 1
        linein = Space(Lof(1))
        Get #1, 1, linein
        Do
            x = Instr(linein, matchtext)
            If x Then
                linein = Left(linein, x - 1) & repltext & Mid(linein, x + matchlen)
            Else
                Exit Do
            End If
        Loop
        Close
        Open filespec For Output As 1
        Print #1, linein;
        Close
        filespec = Dir
    Wend
    L0 += 1
Wend


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
}


import Data.List (tails, elemIndices, isPrefixOf)

replace :: String -> String -> String -> String
replace [] _ xs = xs
replace _ [] xs = xs
replace _ _ []  = []
replace a b xs  = replAll
    where
        -- make substrings, dropping one element each time
        xtails = tails xs
        -- what substrings begin with the string to replace?
        -- get their indices
        matches = elemIndices True $ map (isPrefixOf a) xtails
        -- replace one occurrence
        repl ys n = take n ys ++ b ++ drop (n + length b) ys
        -- replace all occurrences consecutively
        replAll = foldl repl xs matches

replaceInFiles a1 a2 files = do
    f <- mapM readFile files
    return $ map (replace a1 a2) f


procedure main()
globalrepl("Goodbye London","Hello New York","a.txt","b.txt") # variable args for files
end

procedure globalrepl(old,new,files[])

every fn := !files do
   if s := reads(f := open(fn,"bu"),stat(f).size) then {
      writes(seek(f,1),replace(s,old,new))
      close(f)
      }
   else write(&errout,"Unable to open ",fn)
end

link strings # for replace


require'strings'
(1!:2~rplc&('Goodbye London!';'Hello New York!')@(1!:1))"0 files


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);
            }
        }
    }
}


for file
do
  jq -Rr 'gsub($from; $to)' --arg from 'Goodbye London!' --arg to 'Hello New York!' "$file" |
    sponge "$file"
done


/* Global replace in Jsish */
if (console.args.length == 0) {
    console.args.push('-');
}

/* For each file, globally replace "Goodbye London!" with "Hello New York!" */
var fn, data, changed;
for (fn of console.args) {
    /* No args, or an argument of - uses "stdin" (a special Channel name) */
    if (fn == 'stdin') fn = './stdin';
    if (fn == '-') fn = 'stdin';
    try {
        data = File.read(fn);
        /* Jsi supports the m multiline regexp flag */
        changed = data.replace(/Goodbye London!/gm, 'Hello New York!');
        if (changed != data) {
            if (fn == 'stdin') fn = 'stdout'; else fn += '.new';
            var cnt = File.write(fn, changed);
            puts(fn + ":" + cnt, 'updated');
        }
    } catch(err) { puts(err, 'processing', fn); }
}


filenames = ["f1.txt", "f2.txt"]
for filename in filenames
   txt = read(filename, String)
   open(filename, "w") do f
      write(f, replace(txt, "Goodbye London!" => "Hello New York!"))
   end
end


// version 1.2.0

import java.io.File

fun main(args: Array<String>) {
    val files = arrayOf("file1.txt", "file2.txt")
    for (file in files) {
        val f = File(file)
        var text = f.readText()
        println(text)
        text = text.replace("Goodbye London!", "Hello New York!")
        f.writeText(text)
        println(f.readText())
    }
}


#!/usr/bin/lasso9

local(files = array('f1.txt', 'f2.txt'))

with filename in #files
let file = file(#filename)
let content = #file -> readbytes
do {
	#file -> dowithclose => {
		#content -> replace('Goodbye London!', 'Hello New York!')
		#file -> opentruncate
		#file -> writebytes(#content)
	}
}


nomainwin

file$( 1) ="data1.txt"
file$( 2) ="data2.txt"
file$( 3) ="data3.txt"

for i =1 to 3
    open file$( i) for input as #i
        orig$ =input$( #i, lof( #i))
    close #i

    dummy$ =FindReplace$( orig$, "Goodbye London!", "Hello New York!", 1)

    open "RC" +file$( i) for output as #o
        #o dummy$;
    close #o
next i

end

function FindReplace$( FindReplace$, find$, replace$, replaceAll)
'   Target string, string to find, string to replace it with, flag 0/1 for 'replace all occurrences'.
    if ( ( FindReplace$ <>"") and ( find$ <>"") ) then
        fLen =len( find$)
        rLen =len( replace$)
        do
            fPos =instr( FindReplace$, find$, fPos)
            if not( fPos) then exit function
            pre$            =left$( FindReplace$, fPos -1)
            post$           =mid$( FindReplace$, fPos +fLen)
            FindReplace$    =pre$ +replace$ +post$
            fPos            =fPos +( rLen -fLen) +1
        loop while (replaceAll)
    end if
end function


filenames = { "f1.txt", "f2.txt" }

for _, fn in pairs( filenames ) do
    fp = io.open( fn, "r" )
    str = fp:read( "*all" )
    str = string.gsub( str, "Goodbye London!", "Hello New York!" )
    fp:close()

    fp = io.open( fn, "w+" )
    fp:write( str )
    fp:close()
end