when ScrapeButton.Click do
  set ScrapeWeb.Url to SourceTextBox.Text
  call ScrapeWeb.Get

when ScrapeWeb.GotText url,responseCode,responseType,responseContent do
  initialize local Left to split at first text (text: get responseContent, at: PreTextBox.Text)
  initialize local Right to "" in
    set Right to select list item (list: get Left, index: 2)
    set ResultLabel.Text to select list item (list: split at first (text:get Right, at: PostTextBox.Text), index: 1)


use AppleScript version "2.4" -- OS X 10.10 (Yosemite) or later
use framework "Foundation"

on firstDateonWebPage(URLText)
    set |⌘| to current application
    set pageURL to |⌘|'s class "NSURL"'s URLWithString:(URLText)
    -- Fetch the page HTML as data.
    -- The Xcode documentation advises against using dataWithContentsOfURL: over a network,
    -- but I'm guessing this applies to downloading large files rather than a Web page's HTML.
    -- If in doubt, the HTML can be fetched as text instead and converted to data in house.
    set HTMLData to |⌘|'s class "NSData"'s dataWithContentsOfURL:(pageURL)
    -- Or:
    (*
    set {HTMLText, encoding} to |⌘|'s class "NSString"'s stringWithContentsOfURL:(pageURL) ¬
        usedEncoding:(reference) |error|:(missing value)
    set HTMLData to HTMLText's dataUsingEncoding:(encoding)
    *)

    -- Extract the page's visible text from the HTML.
    set straightText to (|⌘|'s class "NSAttributedString"'s alloc()'s initWithHTML:(HTMLData) ¬
        documentAttributes:(missing value))'s |string|()

    -- Use an NSDataDetector to locate the first date in the text. (It's assumed here there'll be one.)
    set dateDetector to |⌘|'s class "NSDataDetector"'s dataDetectorWithTypes:(|⌘|'s NSTextCheckingTypeDate) ¬
        |error|:(missing value)
    set matchRange to dateDetector's rangeOfFirstMatchInString:(straightText) options:(0) ¬
        range:({0, straightText's |length|()})

    -- Return the date text found.
    return (straightText's substringWithRange:(matchRange)) as text
end firstDateonWebPage

firstDateonWebPage("https://www.rosettacode.org/wiki/Talk:Web_scraping")


UrlDownloadToFile, http://tycho.usno.navy.mil/cgi-bin/timer.pl, time.html
FileRead, timefile, time.html
pos := InStr(timefile, "UTC")
msgbox % time := SubStr(timefile, pos - 9, 8)


      SYS "LoadLibrary", "URLMON.DLL" TO urlmon%
      SYS "GetProcAddress", urlmon%, "URLDownloadToFileA" TO UDTF%
      SYS "LoadLibrary", "WININET.DLL" TO wininet%
      SYS "GetProcAddress", wininet%, "DeleteUrlCacheEntryA" TO DUCE%

      url$ = "http://tycho.usno.navy.mil/cgi-bin/timer.pl"
      file$ = @tmp$+"navytime.txt"

      SYS DUCE%, url$
      SYS UDTF%, 0, url$, file$, 0, 0 TO result%
      IF result% ERROR 100, "Download failed"

      file% = OPENIN(file$)
      REPEAT
        text$ = GET$#file%
        IF INSTR(text$, "UTC") PRINT MID$(text$, 5)
      UNTIL EOF#file%
      CLOSE #file%


#include <stdio.h>
#include <string.h>
#include <curl/curl.h>
#include <sys/types.h>
#include <regex.h>

#define BUFSIZE 16384

size_t lr = 0;

size_t filterit(void *ptr, size_t size, size_t nmemb, void *stream)
{
  if ( (lr + size*nmemb) > BUFSIZE ) return BUFSIZE;
  memcpy(stream+lr, ptr, size*nmemb);
  lr += size*nmemb;
  return size*nmemb;
}

int main()
{
  CURL *curlHandle;
  char buffer[BUFSIZE];
  regmatch_t amatch;
  regex_t cregex;

  curlHandle = curl_easy_init();
  curl_easy_setopt(curlHandle, CURLOPT_URL, "http://tycho.usno.navy.mil/cgi-bin/timer.pl");
  curl_easy_setopt(curlHandle, CURLOPT_FOLLOWLOCATION, 1);
  curl_easy_setopt(curlHandle, CURLOPT_WRITEFUNCTION, filterit);
  curl_easy_setopt(curlHandle, CURLOPT_WRITEDATA, buffer);
  int success = curl_easy_perform(curlHandle);
  curl_easy_cleanup(curlHandle);

  buffer[lr] = 0;

  regcomp(&cregex, " UTC", REG_NEWLINE);
  regexec(&cregex, buffer, 1, &amatch, 0);
  int bi = amatch.rm_so;
  while ( bi-- > 0 )
    if ( memcmp(&buffer[bi], "<BR>", 4) == 0 ) break;

  buffer[amatch.rm_eo] = 0;

  printf("%s\n", &buffer[bi+4]);

  regfree(&cregex);
  return 0;
}


class Program
    {
        static void Main(string[] args)
        {
            WebClient wc = new WebClient();
            Stream myStream = wc.OpenRead("http://tycho.usno.navy.mil/cgi-bin/timer.pl");
            string html = "";
            using (StreamReader sr = new StreamReader(myStream))
            {
                while (sr.Peek() >= 0)
                {
                    html = sr.ReadLine();
                    if (html.Contains("UTC"))
                    {
                        break;
                    }
                }

            }
            Console.WriteLine(html.Remove(0, 4));

            Console.ReadLine();
        }
    }


#include <iostream>
#include <string>
#include <boost/asio.hpp>
#include <boost/regex.hpp>
int main()
{
    boost::asio::ip::tcp::iostream s("tycho.usno.navy.mil", "http");
    if(!s)
        std::cout << "Could not connect to tycho.usno.navy.mil\n";
    s  << "GET /cgi-bin/timer.pl HTTP/1.0\r\n"
       << "Host: tycho.usno.navy.mil\r\n"
       << "Accept: */*\r\n"
       << "Connection: close\r\n\r\n" ;
    for(std::string line; getline(s, line); )
    {
        boost::smatch matches;
        if(regex_search(line, matches, boost::regex("<BR>(.+\\s+UTC)") ) )
        {
            std::cout << matches[1] << '\n';
            break;
        }
    }
}


Class Utils.Net [ Abstract ]
{

ClassMethod ExtractHTMLData(pHost As %String = "", pPath As %String = "", pRegEx As %String = "", Output list As %List) As %Status
{
  // implement error handling
  Try {

    // some initialisation
    Set list="", sc=$$$OK

    // check input parameters
    If $Match(pHost, "^([a-zA-Z0-9]([a-zA-Z0-9\-]{0,61}[a-zA-Z0-9])?\.)+[a-zA-Z]{2,6}$")=0 {
      Set sc=$$$ERROR($$$GeneralError, "Invalid host name.")
      Quit
    }

    // create http request and get page
    Set req=##class(%Net.HttpRequest).%New()
    Set req.Server=pHost
    Do req.Get(pPath)

    // check for success
    If $Extract(req.HttpResponse.StatusCode)'=2 {
      Set sc=$$$ERROR($$$GeneralError, "Page not loaded.")
      Quit
    }

    // read http response stream
    Set html=req.HttpResponse.Data
    Set html.LineTerminator=$Char(10)
    Set sc=html.Rewind()

    // read http response stream
    While 'html.AtEnd {
      Set line=html.ReadLine(, .sc, .eol)
      Set pos=$Locate(line, pRegEx)
      If pos {
        Set parse=$Piece($Extract(line, pos, *), $Char(9))
        Set slot=$ListLength(list)+1
        Set $List(list, slot)=parse
      }
    }

  } Catch err {

    // an error has occurred
    If err.Name="<REGULAR EXPRESSION>" {
      Set sc=$$$ERROR($$$GeneralError, "Invalid regular expression.")
    } Else {
      Set sc=$$$ERROR($$$CacheError, $ZError)
    }

  }

  // return status
  Quit sc
}

}


import ceylon.uri {
    parse
}
import ceylon.http.client {
    get
}

shared void run() {

    // apparently the cgi link is deprecated?
    value oldUri = "http://tycho.usno.navy.mil/cgi-bin/timer.pl";
    value newUri = "http://tycho.usno.navy.mil/timer.pl";

    value contents = downloadContents(newUri);
    value time = extractTime(contents);
    print(time else "nothing found");
}

String downloadContents(String uriString) {
    value uri = parse(uriString);
    value request = get(uri);
    value response = request.execute();
    return response.contents;
}

String? extractTime(String contents) =>
        contents
        .lines
        .filter((String element) => element.contains("UTC"))
        .first
        ?.substring(4, 21);


(second (re-find #" (\d{1,2}:\d{1,2}:\d{1,2}) UTC" (slurp "http://tycho.usno.navy.mil/cgi-bin/timer.pl")))


http = require 'http'

CONFIG =
  host: 'tycho.usno.navy.mil'
  path: '/cgi-bin/timer.pl'

# Web scraping code tends to be brittle, and this is no exception.
# The tycho time page does not use highly structured markup, so
# we do a real dirty scrape.
scrape_tycho_ust_time = (text) ->
  for line in text.split '\n'
    matches = line.match /(.*:\d\d UTC)/
    if matches
      console.log matches[0].replace '<BR>', ''
      return
  throw Error("unscrapable page!")

# This is low-level-ish code to get data from a URL. It's
# pretty general purpose, so you'd normally tuck this away
# in a library (or use somebody else's library).
wget = (host, path, cb) ->
  options =
    host: host
    path: path
    headers:
      "Cache-Control": "max-age=0"

  req = http.request options, (res) ->
    s = ''
    res.on 'data', (chunk) ->
      s += chunk
    res.on 'end', ->
      cb s
  req.end()

# Do our web scrape
do ->
  wget CONFIG.host, CONFIG.path, (data) ->
    scrape_tycho_ust_time data


BOA> (let* ((url "http://tycho.usno.navy.mil/cgi-bin/timer.pl")
            (regexp (load-time-value
                     (cl-ppcre:create-scanner "(?m)^.{4}(.+? UTC)")))
            (data (drakma:http-request url)))
       (multiple-value-bind (start end start-regs end-regs)
           (cl-ppcre:scan regexp data)
         (declare (ignore end))
         (when start
           (subseq data (aref start-regs 0) (aref end-regs 0)))))
"Aug. 12, 04:29:51 UTC"


void main() {
    import std.stdio, std.string, std.net.curl, std.algorithm;

    foreach (line; "http://tycho.usno.navy.mil/cgi-bin/timer.pl".byLine)
        if (line.canFind(" UTC"))
            line[4 .. $].writeln;
}


program WebScrape;

{$APPTYPE CONSOLE}

{.$DEFINE DEBUG}

uses
  Classes,
  Winsock;

{ Function to connect to host, send HTTP request and retrieve response }
function DoHTTPGET(const hostName: PAnsiChar; const resource: PAnsiChar; HTTPResponse: TStrings): Boolean;
const
  Port: integer = 80;
  CRLF = #13#10; // carriage return/line feed
var
  WSAData: TWSAData;
  Sock: TSocket;
  SockAddrIn: TSockAddrIn;
  IPAddress: PHostEnt;
  bytesIn: integer;
  inBuffer: array [0..1023] of char;
  Req: string;
begin
  Result := False;
  HTTPResponse.Clear;

  { Initialise use of the Windows Sockets DLL.
    Older Windows versions support Winsock 1.1 whilst newer Windows
    include Winsock 2 but support 1.1.  Therefore, we'll specify
    version 1.1 ($101) as being the highest version of Windows Sockets
    that we can use to provide greatest flexibility.
    WSAData receives details of the Windows Sockets implementation }
  Winsock.WSAStartUp($101, WSAData);
  try

    { Create a socket for TCP/IP usage passing in
      Address family spec: AF_INET (TCP, UDP, etc.)
      Type specification: SOCK_STREAM
      Protocol: IPPROTO_TCP (TCP) }
    Sock := WinSock.Socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
    try

      // Check we have a valid socket
      if (Sock <> INVALID_SOCKET) then
        begin
          // Populate socket address structure
          with SockAddrIn do
            begin
              // Address family specification
              sin_family := AF_INET;
              // Port
              sin_port := htons(Port);
              // Address
              sin_addr.s_addr := inet_addr(hostName);
            end;

          if (SockAddrIn.sin_addr.s_addr = INADDR_NONE) then
            begin
              { As we're using a domain name instead of an
                IP Address, we need to resolve the domain name }
              IPAddress := Winsock.gethostbyname(hostName);

              // Quit if we didn't get an IP Address
              if (IPAddress = nil) then
                Exit;

              // Update the structure with the IP Address
              SockAddrIn.sin_addr.s_addr := PLongint(IPAddress^.h_addr_list^)^;
            end;

          // Try to connect to host
          if (Winsock.connect(Sock, SockAddrIn, SizeOf(SockAddrIn)) <> SOCKET_ERROR) then
            begin
              // OK - Connected

              // Compose our request
              // Each line of the request must be terminated with a carriage return/line feed

              {  The First line specifies method (e.g. GET, POST), path to required resource,
                 and the HTTP version being used.  These three fields are space separated. }
               Req := 'GET '+resource+' HTTP/1.1' + CRLF +

                     // Host: is the only Required header in HTTP 1.1
                     'Host: '+hostName + CRLF +

                     { Persistent connections are the default in HTTP 1.1 but, as we don't want
                       or need one for this exercise, we must include the "Connection: close"
                       header in our request }
                     'Connection: close' + CRLF +

                     CRLF; // Request must end with an empty line!

              // Try to send the request to the host
              if (Winsock.send(Sock,Req[1],Length(Req),0) <> SOCKET_ERROR) then
                begin
                  // Initialise incoming data buffer (i.e. fill array with nulls)
                  FillChar(inBuffer,SizeOf(inBuffer),#0);
                  // Loop until nothing left to read
                  repeat
                    // Read incoming data from socket
                    bytesIn := Winsock.recv(Sock, inBuffer, SizeOf(inBuffer), 0);
                    // Assign buffer to Stringlist
                    HTTPResponse.Text := HTTPResponse.Text + Copy(string(inBuffer),1,bytesIn);
                  until
                    (bytesIn <= 0) or (bytesIn = SOCKET_ERROR);

                  { Our list of response strings should
                    contain at least 1 line }
                  Result := HTTPResponse.Count > 0;
                end;

             end;

        end;

    finally
      // Close our socket
      Winsock.closesocket(Sock);
    end;

  finally
    { This causes our application to deregister itself from this
      Windows Sockets implementation and allows the implementation
      to free any resources allocated on our behalf. }
    Winsock.WSACleanup;
  end;

end;

{ Simple function to locate and return the UTC time from the
  request sent to http://tycho.usno.navy.mil/cgi-bin/timer.pl
  The HTTPResponse parameter contains both the HTTP Headers and
  the HTML served up by the requested resource. }
function ParseResponse(HTTPResponse: TStrings): string;
var
  i: Integer;
begin
  Result := '';

  { Check first line for server response code
    We want something like this: HTTP/1.1 200 OK }
  if Pos('200',HTTPResponse[0]) > 0 then
    begin
      for i := 0 to Pred(HTTPResponse.Count) do
        begin
          { The line we're looking for is something like this:
            <BR>May. 04. 21:55:19 UTC Universal Time }

          // Check each line
          if Pos('UTC',HTTPResponse[i]) > 0 then
            begin
              Result := Copy(HTTPResponse[i],5,Pos('UTC',HTTPResponse[i])-1);
              Break;
            end;

        end;
    end
    else
    Result := 'HTTP Error: '+HTTPResponse[0];
end;

const
  host: PAnsiChar = 'tycho.usno.navy.mil';
  res : PAnsiChar = '/cgi-bin/timer.pl';

var
  Response: TStrings;

begin
  { A TStringList is a TStrings descendant class
    that is used to store and manipulate a list
    of strings.

    Instantiate a stringlist class to
    hold the results of our HTTP GET }
  Response := TStringList.Create;
  try
    // Try an HTTP GET request
    if DoHTTPGET(host,res,Response) then
      begin
        {$IFDEF DEBUG}
        { Write the entire response to
          the console window }
        Writeln(Response.text);
        {$ELSE}
        { Parse the response and write the
          result to the console window }
        Writeln(ParseResponse(Response));
        {$ENDIF DEBUG}
      end
      else
      Writeln('Error retrieving data');

  finally
    Response.Free;
  end;

  // Keep console window open
  Readln;

end.


interp.waitAtTop(when (def html := <http://tycho.usno.navy.mil/cgi-bin/timer.pl>.getText()) -> {
    def rx`(?s).*>(@time.*? UTC).*` := html
    println(time)
})


-module(scraping).
-export([main/0]).
-define(Url, "http://tycho.usno.navy.mil/cgi-bin/timer.pl").
-define(Match, "<BR>(.+ UTC)").

main() ->
  inets:start(),
  {ok, {_Status, _Header, HTML}} = httpc:request(?Url),
  {match, [Time]} = re:run(HTML, ?Match, [{capture, all_but_first, binary}]),
  io:format("~s~n",[Time]).


open System
open System.Net
open System.Text.RegularExpressions

async {
    use wc = new WebClient()
    let! html = wc.AsyncDownloadString(Uri("http://tycho.usno.navy.mil/cgi-bin/timer.pl"))
    return Regex.Match(html, @"<BR>(.+ UTC)").Groups.[1].Value
}
|> Async.RunSynchronously
|> printfn "%s"


USING: http.client io sequences ;

"http://tycho.usno.navy.mil/cgi-bin/timer.pl" http-get nip
[ "UTC" swap start [ 9 - ] [ 1 - ] bi ] keep subseq print


include unix/socket.fs

: extract-time ( addr len type len -- time len )
  dup >r
  search 0= abort" that time not present!"
  dup >r
  begin -1 /string  over 1- [email protected] [char] > = until       \ seek back to <BR> at start of line
  r> - r> + ;

s" tycho.usno.navy.mil" 80 open-socket
dup s\" GET /cgi-bin/timer.pl HTTP/1.0\n\n" rot write-socket
dup pad 4096 read-socket
s\" \r\n\r\n" search 0= abort" can't find headers!"   \ skip headers
s" UTC" extract-time type cr
close-socket


import io.Source

case Source.fromURL( 'http://tycho.usno.navy.mil/cgi-bin/timer.pl', 'UTF-8' ).getLines().find( ('Eastern' in) ) of
  Some( time ) -> println( time.substring(4) )
  None         -> error( 'Easter time not found' )


Public Sub Main()
Dim sWeb, sTemp, sOutput As String                                          'Variables

Shell "wget -O /tmp/web http://tycho.usno.navy.mil/cgi-bin/timer.pl" Wait   'Use 'wget' to save the web file in /tmp/

sWeb = File.Load("/tmp/web")                                                'Open file and store in sWeb

For Each sTemp In Split(sWeb, gb.NewLine)                                   'Split the file by NewLines..
  If InStr(sTemp, "UTC") Then                                               'If the line contains "UTC" then..
    sOutPut = sTemp                                                         'Extract the line into sOutput
    Break                                                                   'Get out of here
  End If
Next

Print Mid(sOutput, 5)                                                       'Print the result without the '<BR>' tag

End


package main

import (
    "bytes"
    "encoding/xml"
    "fmt"
    "io"
    "net/http"
    "regexp"
    "time"
)

func main() {
    resp, err := http.Get("http://tycho.usno.navy.mil/cgi-bin/timer.pl")
    if err != nil {
        fmt.Println(err) // connection or request fail
        return
    }
    defer resp.Body.Close()
    var us string
    var ux int
    utc := []byte("UTC")
    for p := xml.NewDecoder(resp.Body); ; {
        t, err := p.RawToken()
        switch err {
        case nil:
        case io.EOF:
            fmt.Println("UTC not found")
            return
        default:
            fmt.Println(err) // read or parse fail
            return
        }
        if ub, ok := t.(xml.CharData); ok {
            if ux = bytes.Index(ub, utc); ux != -1 {
                // success: found a line with the string "UTC"
                us = string([]byte(ub))
                break
            }
        }
    }
    // first thing to try: parsing the expected date format
    if t, err := time.Parse("Jan. 2, 15:04:05 UTC", us[:ux+3]); err == nil {
        fmt.Println("parsed UTC:", t.Format("January 2, 15:04:05"))
        return
    }
    // fallback: search for anything looking like a time and print that
    tx := regexp.MustCompile("[0-2]?[0-9]:[0-5][0-9]:[0-6][0-9]")
    if justTime := tx.FindString(us); justTime > "" {
        fmt.Println("found UTC:", justTime)
        return
    }
    // last resort: just print the whole element containing "UTC" and hope
    // there is a human readable time in there somewhere.
    fmt.Println(us)
}


def time = "unknown"
def text = new URL('http://tycho.usno.navy.mil/cgi-bin/timer.pl').eachLine { line ->
    def matcher = (line =~ "<BR>(.+) UTC")
    if (matcher.find()) {
        time = matcher[0][1]
    }
}
println "UTC Time was '$time'"


import Data.List
import Network.HTTP (simpleHTTP, getResponseBody, getRequest)

tyd = "http://tycho.usno.navy.mil/cgi-bin/timer.pl"

readUTC = simpleHTTP (getRequest tyd)>>=
            fmap ((!!2).head.dropWhile ("UTC"`notElem`).map words.lines). getResponseBody>>=putStrLn


procedure main()
m := open(url := "http://tycho.usno.navy.mil/cgi-bin/timer.pl","m") | stop("Unable to open ",url)
every (p := "") ||:= |read(m)                                                    # read the page into a single string
close(m)

map(p) ? ( tab(find("
")), ="
", write("UTC time=",p[&pos:find(" utc")]))  # scrape and show
end


   require 'web/gethttp'

   _8{. ' UTC' taketo gethttp 'http://tycho.usno.navy.mil/cgi-bin/timer.pl'
04:32:44


import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;

public class WebTime{
  public static void main(String[] args){
    try{
      URL address = new URL(
          "http://tycho.usno.navy.mil/cgi-bin/timer.pl");
      URLConnection conn = address.openConnection();
      BufferedReader in = new BufferedReader(
          new InputStreamReader(conn.getInputStream()));
      String line;
      while(!(line = in.readLine()).contains("UTC"));
      System.out.println(line.substring(4));
    }catch(IOException e){
      System.err.println("error connecting to server.");
      e.printStackTrace();
    }
  }
}


var req = new XMLHttpRequest();
req.onload = function () {
  var re = /[JFMASOND].+ UTC/; //beginning of month name to 'UTC'
  console.log(this.responseText.match(re)[0]);
};
req.open('GET', 'http://tycho.usno.navy.mil/cgi-bin/timer.pl', true);
req.send();


#!/bin/bash
  curl -Ss 'http://tycho.usno.navy.mil/cgi-bin/timer.pl' |\
    jq -R -r 'if index(" UTC") then .[4:] else empty end'


using Requests, Printf

function getusnotime()
    const url = "http://tycho.usno.navy.mil/timer.pl"
    s = try
        get(url)
        catch err
        @sprintf "get(%s)\n   => %s" url err
    end
    isa(s, Requests.Response) || return (s, false)
    t = match(r"(?<=<BR>)(.*?UTC)", readstring(s))
    isa(t, RegexMatch) || return (@sprintf("raw html:\n %s", readstring(s)), false)
    return (t.match, true)
end

(t, issuccess) = getusnotime();

if issuccess
    println("The USNO time is ", t)
else
    println("Failed to fetch UNSO time:\n", t)
end


// version 1.1.3

import java.net.URL
import java.io.InputStreamReader
import java.util.Scanner

fun main(args: Array<String>) {
    val url = URL("http://tycho.usno.navy.mil/cgi-bin/timer.pl")
    val isr = InputStreamReader(url.openStream())
    val sc = Scanner(isr)
    while (sc.hasNextLine()) {
        val line = sc.nextLine()
        if ("UTC" in line) {
            println(line.drop(4).take(17))
            break
        }
    }
    sc.close()
}


/* have to be used
local(raw_htmlstring = '<TITLE>What time is it?</TITLE>

 US Naval Observatory Master Clock Time

Jul. 27, 22:57:22 UTC   Universal Time

Jul. 27, 06:57:22 PM EDT  Eastern Time

Jul. 27, 05:57:22 PM CDT  Central Time

Jul. 27, 04:57:22 PM MDT  Mountain Time

Jul. 27, 03:57:22 PM PDT  Pacific Time

Jul. 27, 02:57:22 PM AKDT Alaska Time

Jul. 27, 12:57:22 PM HAST Hawaii-Aleutian Time

')
*/

// should be used
local(raw_htmlstring = string(include_url('http://tycho.usno.navy.mil/cgi-bin/timer.pl')))

local(
  reg_exp = regexp(-find = `<br>(.*?) UTC`, -input = #raw_htmlstring, -ignorecase),
  datepart_txt =  #reg_exp -> find ? #reg_exp -> matchstring(1) | string
)

#datepart_txt
'
'
// added bonus showing how parsed string can be converted to date object
local(mydate = date(#datepart_txt, -format = `MMM'.' dd',' HH:mm:ss`))
#mydate -> format(`YYYY-MM-dd HH:mm:ss`)


if DownloadToFile("http://tycho.usno.navy.mil/cgi-bin/timer.pl", DefaultDir$ + "\timer.htm") = 0 then
        open DefaultDir$ + "\timer.htm" for input as #f
                html$ = lower$(input$(#f, LOF(#f)))
        close #f

        a= instr( html$, "utc" )-1
        print "UTC";mid$( html$, a-9,9)

    end if

end

function DownloadToFile(urlfile$, localfile$)
    open "URLmon" for dll as #url
    calldll #url, "URLDownloadToFileA",_
    0 as long,_         'null
    urlfile$ as ptr,_   'url to download
    localfile$ as ptr,_ 'save file name
    0 as long,_         'reserved, must be 0
    0 as long,_         'callback address, can be 0
    DownloadToFile as ulong  '0=success
    close #url
end function


local http = require("socket.http")    -- Debian package is 'lua-socket'

function scrapeTime (pageAddress, timeZone)
    local page = http.request(pageAddress)
    if not page then return "Cannot connect" end
    for line in page:gmatch("[^<BR>]*") do
        if line:match(timeZone) then
            return line:match("%d+:%d+:%d+")
        end
    end
end

local url = "http://tycho.usno.navy.mil/cgi-bin/timer.pl"
print(scrapeTime(url, "UTC"))


Module Web_scraping {
	Print "Web scraping"
	function GetTime$(a$, what$="UTC") {
		document a$ ' change string to document
		find a$, what$  ' place data to stack
		Read find_pos
		if find_pos>0 then
			read par_order, par_pos
			b$=paragraph$(a$, par_order)
			k=instr(b$,">")
			if k>0 then if k<par_pos then b$=mid$(b$,k+1) :par_pos-=k
			k=rinstr(b$,"<")
			if k>0 then if k>par_pos then b$=Left(b$,k-1)
			=b$
		end if
	}
	declare msxml2 "MSXML2.XMLHTTP.6.0"
	rem print type$(msxml2)="IXMLHTTPRequest"
	Url$ = "http://tycho.usno.navy.mil/cgi-bin/timer.pl"
	try ok {
		method msxml2, "Open", "GET", url$, false
		method msxml2,"Send"
		with msxml2,"responseText" as txt$
		Print GetTime$(txt$)
	}
	If error or not ok then Print Error$
	declare msxml2 nothing
}
Web_scraping


test = StringSplit[Import["http://tycho.usno.navy.mil/cgi-bin/timer.pl"], "\n"];
Extract[test, [email protected][StringFreeQ[test, "UTC"], False]]


s  = urlread('http://tycho.usno.navy.mil/cgi-bin/timer.pl');
ix = [findstr(s,'<BR>'), length(s)+1];
for k = 2:length(ix)
     tok = s(ix(k-1)+4:ix(k)-1);
     if findstr(tok,'UTC')
  disp(tok);
     end;
end;


'Entered by AykayayCiti -- Earl L. Montgomery
url_name = "http://tycho.usno.navy.mil/cgi-bin/timer.pl"
url_data = Network.GetWebPageContents(url_name)
find = "UTC"
' the length from the UTC to the time is -18 so we need
' to subtract from the UTC position
pos = Text.GetIndexOf(url_data,find)-18
result = Text.GetSubText(url_data,pos,(18+3)) 'plus 3 to add the UTC
TextWindow.WriteLine(result)

'you can eleminate a line of code by putting the
' GetIndexOf insde the GetSubText
'result2 = Text.GetSubText(url_data,Text.GetIndexOf(url_data,find)-18,(18+3))
'TextWindow.WriteLine(result2)


alias utc {
  sockclose UTC
  sockopen UTC tycho.usno.navy.mil 80
}

on *:SOCKOPEN:UTC: {
  sockwrite -n UTC GET /cgi-bin/timer.pl HTTP/1.1
  sockwrite -n UTC Host: tycho.usno.navy.mil
  sockwrite UTC $crlf
}

on *:SOCKREAD:UTC: {
  sockread %UTC
  while ($sockbr) {
    if (
*Universal Time iswm %UTC) {
      echo -ag $remove(%UTC,
,$chr(9),Universal Time)
      unset %UTC
      sockclose UTC
      return
    }
    sockread %UTC
  }
}


/* NetRexx */
options replace format comments java crossref symbols binary

parse arg full_short .
if 'FULL'.abbrev(full_short.upper(), 1) then
  dateFull = isTrue()
else
  dateFull = isFalse()
do
  timeURL = java.net.URL('http://tycho.usno.navy.mil/cgi-bin/timer.pl')
  conn = timeURL.openConnection()
  ibr = BufferedReader(InputStreamReader(conn.getInputStream()))
  line = Rexx
  loop label readLoop while ibr.ready()
    line = ibr.readLine()
    if line = null then leave readLoop
    line = line.translate(' ', '\t')
    if line.wordpos('UTC') > 0 then do
      parse line . '>'       udatetime 'UTC' . -
            0    . '>' . ',' utime     'UTC' .
      if dateFull then
        say udatetime.strip() 'UTC'
      else
        say utime.strip()
      leave readLoop
      end
    end readLoop
  ibr.close()
catch ex = IOException
  ex.printStackTrace()
end

method isTrue() public constant returns boolean
  return 1 == 1
method isFalse() public constant returns boolean
  return \isTrue()


import httpclient, strutils

var client = newHttpClient()

var res: string
for line in client.getContent("https://rosettacode.org/wiki/Talk:Web_scraping").splitLines:
  let k = line.find("UTC")
  if k >= 0:
    res = line[0..(k - 3)]
    let k = res.rfind("</a>")
    res = res[(k + 6)..^1]
    break
echo if res.len > 0: res else: "No date/time found."


use Net;
use IO;
use Structure;

bundle Default {
  class Scrape {
    function : Main(args : String[]) ~ Nil {
      client := HttpClient->New();
      lines := client->Get("http://tycho.usno.navy.mil/cgi-bin/timer.pl", 80);

       i := 0;
       found := false;
      while(found <> true & i < lines->Size()) {
         line := lines->Get(i)->As(String);
        index := line->Find("UTC");
        if(index > -1) {
          time := line->SubString(index - 9, 9)->Trim();
          time->PrintLine();
          found := true;
        };
        i += 1;
      };
    }
  }
}


let () =
  let _,_, page_content = make_request ~url:Sys.argv.(1) ~kind:GET () in

  let lines = Str.split (Str.regexp "\n") page_content in
  let str =
    List.find
      (fun line ->
        try ignore(Str.search_forward (Str.regexp "UTC") line 0); true
        with Not_found -> false)
      lines
  in
  let str = Str.global_replace (Str.regexp "<BR>") "" str in
  print_endline str;
;;


/* load the RexxcURL library */
Call RxFuncAdd 'CurlLoadFuncs', 'rexxcurl', 'CurlLoadFuncs'
Call CurlLoadFuncs

url = "http://tycho.usno.navy.mil/cgi-bin/timer.pl"

/* get a curl session */
curl = CurlInit()
if curl \= ''
then do
   call CurlSetopt curl, 'URL', Url
   if curlerror.intcode \= 0 then exit
   call curlSetopt curl, 'OUTSTEM', 'stem.'
   if curlerror.intcode \= 0 then exit
   call CurlPerform curl

   /* content is in a stem - lets get it all in a string */
   content = stem.~allItems~makestring('l')
   /* now parse out utc time */
   parse var content content 'Universal Time' .
   utcTime = content~substr(content~lastpos('<BR>') + 4)
   say utcTime
end


declare
  [Regex] = {Module.link ['x-oz://contrib/regex']}

  fun {GetPage Url}
     F = {New Open.file init(url:Url)}
     Contents = {F read(list:$ size:all)}
  in
     {F close}
     Contents
  end

  fun {GetDateString Doc}
     case {Regex.search "<BR>([A-Za-z0-9:., ]+ UTC)" Doc}
     of match(1:S#E ...) then {List.take {List.drop Doc S} E-S+1}
     end
  end

  Url = "http://tycho.usno.navy.mil/cgi-bin/timer.pl"
in
  {System.showInfo {GetDateString {GetPage Url}}}


<@ DEFAREPRS>Rexx Parse</@>
<@ DEFPRSLIT>Rexx Parse|'<BR>' UTCtime 'UTC'</@>
<@ LETVARURL>timer|http://tycho.usno.navy.mil/cgi-bin/timer.pl</@>
<@ ACTRPNPRSVAR>Rexx Parse|timer</@>
<@ SAYVAR>UTCtime</@>


use LWP::Simple;

my $url = 'http://tycho.usno.navy.mil/cgi-bin/timer.pl';
get($url) =~ /<BR>(.+? UTC)/
    and print "$1\n";


--
-- demo\rosetta\web_scrape.exw
-- ===========================
--
without js -- (libcurl)
include builtins\libcurl.e
include builtins\timedate.e

object res = curl_easy_perform_ex("https://rosettacode.org/wiki/Talk:Web_scraping")
if string(res) then
    res = split(res,'\n')
    for i=1 to length(res) do
        integer k = match("UTC",res[i])
        if k then
            string line = res[i] -- (debug aid)
            res = line[1..k-3]
            k = rmatch("</a>",res)
            res = trim(res[k+5..$])
            exit
        end if
    end for
    ?res
    if string(res) then
        timedate td = parse_date_string(res, {"hh:mm, d Mmmm yyyy"})
        ?format_timedate(td,"Dddd Mmmm ddth yyyy h:mpm")
    end if
else
    ?{"some error",res,curl_easy_strerror(res)}
end if


<?

$contents = file('http://tycho.usno.navy.mil/cgi-bin/timer.pl');
foreach ($contents as $line){
  if (($pos = strpos($line, ' UTC')) === false) continue;
  echo subStr($line, 4, $pos - 4); //Prints something like "Dec. 06, 16:18:03"
  break;
}


(load "@lib/http.l")

(client "tycho.usno.navy.mil" 80 "cgi-bin/timer.pl"
   (when (from "<BR>")
      (pack (trim (till "U"))) ) )


$wc = New-Object Net.WebClient
$html = $wc.DownloadString('http://tycho.usno.navy.mil/cgi-bin/timer.pl')
$html -match ', (.*) UTC' | Out-Null
Write-Host $Matches[1]


URLDownloadToFile_( #Null, "http://tycho.usno.navy.mil/cgi-bin/timer.pl", "timer.htm", 0, #Null)
ReadFile(0, "timer.htm")
While Not Eof(0)    :    Text$ + ReadString(0)    :    Wend
MessageRequester("Time", Mid(Text$, FindString(Text$, "UTC", 1) - 9 , 8))


import urllib
page = urllib.urlopen('http://tycho.usno.navy.mil/cgi-bin/timer.pl')
for line in page:
    if ' UTC' in line:
        print line.strip()[4:]
        break
page.close()


all_lines <- readLines("http://tycho.usno.navy.mil/cgi-bin/timer.pl")
utc_line <- grep("UTC", all_lines, value = TRUE)
matched <- regexpr("(\\w{3}.*UTC)", utc_line)
utc_time_str <- substring(line, matched, matched + attr(matched, "match.length") - 1L)


#lang racket
(require net/url)
((compose1 car (curry regexp-match #rx"[^ <>][^<>]+ UTC")
           port->string get-pure-port string->url)
 "https://tycho.usno.navy.mil/cgi-bin/timer.pl")


# 20210301 Updated Raku programming solution

use HTTP::Client; # https://github.com/supernovus/perl6-http-client/

#`[ Site inaccessible since 2019 ?
my $site = "http://tycho.usno.navy.mil/cgi-bin/timer.pl";
HTTP::Client.new.get($site).content.match(/'
'( .+? <ws> UTC )/)[0].say
# ]

my $site = "https://www.utctime.net/";
my $matched = HTTP::Client.new.get($site).content.match(
   /'UTC	'( .*Z )'	'/
)[0];

say $matched;
#$matched = '12321321:412312312 123';
with DateTime.new($matched.Str) {
   say 'The fetch result seems to be of a valid time format.'
} else {
   CATCH { put .^name, ': ', .Str }
}


rebol [
  Title: "Web Scraping"
  URL: http://rosettacode.org/wiki/Web_Scraping
]

; Notice that REBOL understands unquoted URL's:

service: http://tycho.usno.navy.mil/cgi-bin/timer.pl

; The 'read' function can read from any data scheme that REBOL knows
; about, which includes web URLs. NOTE: Depending on your security
; settings, REBOL may ask you for permission to contact the service.

html: read service

; I parse the HTML to find the first
 (note the unquoted HTML tag
; -- REBOL understands those too), then copy the current time from
; there to the "UTC" terminator.

; I have the "to end" in the parse rule so the parse will succeed.
; Not strictly necessary once I've got the time, but good practice.

parse html [thru
 copy current thru "UTC" to end]

print ["Current UTC time:" current]


require "open-uri"

open('http://tycho.usno.navy.mil/cgi-bin/timer.pl') do |p|
  p.each_line do |line|
    if line =~ /UTC/
      puts line.match(/ (\d{1,2}:\d{1,2}:\d{1,2}) /)
      break
    end
  end
end


// 202100302 Rust programming solution

use std::io::Read;
use regex::Regex;

fn main() {

   let client   = reqwest::blocking::Client::new();
   let site     = "https://www.utctime.net/";
   let mut res  = client.get(site).send().unwrap();
   let mut body = String::new();

   res.read_to_string(&mut body).unwrap();

   let re   = Regex::new(r#"UTC	(.*Z)	"#).unwrap();
   let caps = re.captures(&body).unwrap();

   println!("Result : {:?}", caps.get(1).unwrap().as_str());
}


import scala.io.Source

object WebTime extends Application {
  val text = Source.fromURL("http://tycho.usno.navy.mil/cgi-bin/timer.pl")
  val utc = text.getLines.find(_.contains("UTC"))
  utc match {
    case Some(s) => println(s.substring(4))
    case _ => println("error")
  }
}


; Use the regular expression module to parse the url
(use-modules (ice-9 regex) (ice-9 rdelim))

; Variable to store result
(define time "")

; Set the url and parse the hostname, port, and path into variables
(define url "http://tycho.usno.navy.mil/cgi-bin/timer.pl")
(define r (make-regexp "^(http://)?([^:/]+)(:)?(([0-9])+)?(/.*)?" regexp/icase))
(define host (match:substring (regexp-exec r url) 2))
(define port (match:substring (regexp-exec r url) 4))
(define path (match:substring (regexp-exec r url) 6))

; Set port to 80 if it wasn't set above and convert from a string to a number
(if (eq? port #f) (define port "80"))
(define port (string->number port))

; Connect to remote host on specified port
(let ((s (socket PF_INET SOCK_STREAM 0)))
        (connect s AF_INET (car (hostent:addr-list (gethostbyname host))) port)

; Send a HTTP request for the specified path
        (display "GET " s)
        (display path s)
        (display " HTTP/1.0\r\n\r\n" s)

        (set! r (make-regexp "<BR>(.+? UTC)"))
        (do ((line (read-line s) (read-line s))) ((eof-object? line))
                (if (regexp-match? (regexp-exec r line))
                        (set! time (match:substring (regexp-exec r line) 1)))))

; Display result
(display time)
(newline)


$ include "seed7_05.s7i";
  include "gethttp.s7i";

const proc: main is func
  local
    var string: pageWithTime is "";
    var integer: posOfUTC is 0;
    var integer: posOfBR is 0;
    var string: timeStri is "";
  begin
    pageWithTime := getHttp("tycho.usno.navy.mil/cgi-bin/timer.pl");
    posOfUTC := pos(pageWithTime, "UTC");
    if posOfUTC <> 0 then
      posOfBR := rpos(pageWithTime, "<BR>", posOfUTC);
      if posOfBR <> 0 then
        timeStri := pageWithTime[posOfBR + 4 .. pred(posOfUTC)];
        writeln(timeStri);
      end if;
    end if;
  end func;


var ua = frequire('LWP::Simple');
var url = 'http://tycho.usno.navy.mil/cgi-bin/timer.pl';
var match = /<BR>(.+? UTC)/.match(ua.get(url));
say match[0] if match;


val getTime =  fn url =>
  let
   val fname       = "/tmp/fConv" ^ (String.extract (Time.toString (Posix.ProcEnv.time()),7,NONE) );
   val shellCommand = " fetch -o - \""^ url ^"\" | sed -ne 's/^.*alt=.Los Angeles:\\(.* (Daylight Saving)\\).*$/\\1/p' " ;
    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 =TextIO.openIn fname
     in
        ( Posix.Process.sleep (Time.fromReal 0.5) ;
          TextIO.inputLine fin  before
	  (TextIO.closeIn fin ; OS.FileSys.remove fname )
	)
     end
   else
     ( OS.Process.system (  shellCommand ^ " > " ^ fname  ^ " 2>&1 "     ) ;
      SOME "" before OS.Process.exit OS.Process.success
     )
end;

print ( valOf (getTime "http://www.time.org"));


package require http

set request [http::geturl "http://tycho.usno.navy.mil/cgi-bin/timer.pl"]
if {[regexp -line {<BR>(.* UTC)} [http::data $request] --> utc]} {
    puts $utc
}


e, page = require('request').get! 'http://tycho.usno.navy.mil/cgi-bin/timer.pl'
l = line for line in page.body.split('\n') when line.indexOf('UTC')>0
console.log l.substr(4,l.length-20)


$$ MODE TUSCRIPT
SET time = REQUEST ("http://tycho.usno.navy.mil/cgi-bin/timer.pl")
SET utc  = FILTER  (time,":*UTC*:",-)


@(next @(open-command "wget -c http://tycho.usno.navy.mil/cgi-bin/timer.pl -O - 2> /dev/null"))
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 3.2 Final"//EN>

<TITLE>What time is it?</TITLE>

 US Naval Observatory Master Clock Time

@(collect :vars (MO DD HH MM SS (PM "  ") TZ TZNAME))

@MO. @DD, @HH:@MM:@SS @(maybe)@{PM /PM/} @(end)@[email protected]/\t+/@TZNAME
@  (until)

@/.*/
@(end)

 US Naval Observatory

@(output)
@  (repeat)
@[email protected] @HH:@MM:@SS @PM @TZ
@  (end)
@(end)


#!/bin/sh
curl -s http://tycho.usno.navy.mil/cgi-bin/timer.pl |
   sed -ne 's/^<BR>\(.* UTC\).*$/\1/p'


#import std
#import cli

#executable ('parameterized','')

whatime =

<.file$[contents: --<''>]>+ -+
   @hm skip/*4+ ~=(9%cOi&)-~l*+ *~ ~&K3/'UTC',
   (ask bash)/0+ -[wget -O - http://tycho.usno.navy.mil/cgi-bin/timer.pl]-!+-


Rem add Microsoft VBScript Regular Expression X.X to your Tools References

Function GetUTC() As String
    Url = "http://tycho.usno.navy.mil/cgi-bin/timer.pl"
    With CreateObject("MSXML2.XMLHTTP.6.0")
        .Open "GET", Url, False
        .send
        arrt = Split(.responseText, vbLf)
    End With
    For Each t In arrt
        If InStr(t, "UTC") Then
            GetUTC = StripHttpTags(t)

            Exit For
        End If
    Next
End Function

Function StripHttpTags(s)
    With New RegExp
        .Global = True
        .Pattern = "\<.+?\>"
        If .Test(s) Then
            StripHttpTags = .Replace(s, "")
        Else
            StripHttpTags = s
        End If
    End With
End Function

Sub getTime()
    Rem starting point
    Dim ReturnValue As String
    ReturnValue = GetUTC
    Rem debug.print can be removed
    Debug.Print ReturnValue
    MsgBox (ReturnValue)
End Sub


Function GetUTC() As String
    Url = "http://tycho.usno.navy.mil/cgi-bin/timer.pl"
    With CreateObject("MSXML2.XMLHTTP.6.0")
        .Open "GET", Url, False
        .send
        arrt = Split(.responseText, vbLf)
    End With
    For Each t In arrt
        If InStr(t, "UTC") Then
            GetUTC = StripHttpTags(t)

            Exit For
        End If
    Next
End Function

Function StripHttpTags(s)
    With New RegExp
        .Global = True
        .Pattern = "\<.+?\>"
        If .Test(s) Then
            StripHttpTags = .Replace(s, "")
        Else
            StripHttpTags = s
        End If
    End With
End Function

WScript.StdOut.Write GetUTC
WScript.StdOut.WriteLine


Imports System.Net
Imports System.IO
        Dim client As WebClient = New WebClient()
        Dim content As String = client.DownloadString("http://tycho.usno.navy.mil/cgi-bin/timer.pl")
        Dim sr As New StringReader(content)
        While sr.peek <> -1
            Dim s As String = sr.ReadLine
            If s.Contains("UTC") Then
                Dim time As String() = s.Substring(4).Split(vbTab)
                Console.WriteLine(time(0))
            End If
        End While


/* web_scraping.wren */

import "./pattern" for Pattern

var CURLOPT_URL = 10002
var CURLOPT_FOLLOWLOCATION = 52
var CURLOPT_WRITEFUNCTION = 20011
var CURLOPT_WRITEDATA = 10001

var BUFSIZE = 16384

foreign class Buffer {
    construct new(size) {}

    // returns buffer contents as a string
    foreign value
}

foreign class Curl {
    construct easyInit() {}

    foreign easySetOpt(opt, param)

    foreign easyPerform()

    foreign easyCleanup()
}

var buffer = Buffer.new(BUFSIZE)
var curl = Curl.easyInit()
curl.easySetOpt(CURLOPT_URL, "https://rosettacode.org/wiki/Talk:Web_scraping")
curl.easySetOpt(CURLOPT_FOLLOWLOCATION, 1)
curl.easySetOpt(CURLOPT_WRITEFUNCTION, 0) // write function to be supplied by C
curl.easySetOpt(CURLOPT_WRITEDATA, buffer)

curl.easyPerform()
curl.easyCleanup()

var html = buffer.value
var ix = html.indexOf("(UTC)")
if (ix == -1) {
    System.print("UTC time not found.")
    return
}
var p = Pattern.new("/d/d:/d/d, #12/d +1/a =4/d")
var m = p.find(html[(ix - 30).max(0)...ix])
System.print(m.text)


$ xidel -s "https://www.rosettacode.org/wiki/Talk:Web_scraping" -e '
  //p[1]/text()[last()]
'
 20:53, 20 August 2008 (UTC)

$ xidel -s "https://www.rosettacode.org/wiki/Talk:Web_scraping" -e '
  x:parse-dateTime(//p[1]/text()[last()],'hh:nn, dd mmmm yyyy')
'
2008-08-20T20:53:00

$ xidel -s "https://www.rosettacode.org/wiki/Talk:Web_scraping" -e '
  adjust-dateTime-to-timezone(
    x:parse-dateTime(//p[1]/text()[last()],'hh:nn, dd mmmm yyyy'),
    dayTimeDuration('PT0H')
  )
'
$ xidel -s "https://www.rosettacode.org/wiki/Talk:Web_scraping" -e '
  x:parse-dateTime(//p[1]/text()[last()],'hh:nn, dd mmmm yyyy')
  ! adjust-dateTime-to-timezone(.,dayTimeDuration('PT0H'))
'
$ xidel -s "https://www.rosettacode.org/wiki/Talk:Web_scraping" -e '
  x:parse-dateTime(//p[1]/text()[last()],'hh:nn, dd mmmm yyyy')
  => adjust-dateTime-to-timezone(dayTimeDuration('PT0H'))
'
2008-08-20T20:53:00Z


const HOST="tycho.usno.navy.mil", PORT=80, dir="/cgi-bin/timer.pl";
get:="GET %s HTTP/1.0\r\nHost: %s:%s\r\n\r\n".fmt(dir,HOST,PORT);
server:=Network.TCPClientSocket.connectTo(HOST,PORT);
server.write(get);       // send request to web serer
data:=server.read(True); // read data from web server

data.seek(data.find("UTC")); // middle of line
c:=data.seek(Void,0);       // start of line
line:=data[c,data.seek(Void,1)-c].text;
line.print(); // the HTML UTC line

re:=RegExp(0'|.*(\d\d:\d\d:\d\d)|);  // get time
re.search(line);
re.matched[1].println();


L(filename) fs:list_dir(‘/foo/bar’)
   I filename.ends_with(‘.mp3’)
      print(filename)


;
; Non-recursive directory walk for Motorola 68000 under AmigaOs 2.04+ by Thorham
;

execBase equ 4

;
; from exec includes
;
_LVOOpenLibrary equ -552
_LVOCloseLibrary equ -414
_LVOAllocVec equ -684
_LVOFreeVec equ -690

MEMF_ANY equ 0

;
; from dos includes
;
_LVOVPrintf equ -954
_LVOExamine equ -102
_LVOExNext equ -108
_LVOLock equ -84
_LVOUnLock equ -90
_LVOParsePatternNoCase equ -966
_LVOMatchPatternNoCase equ -972

ACCESS_READ equ -2
                    rsset   0
fib_DiskKey         rs.l    1
fib_DirEntryType    rs.l    1
fib_FileName        rs.b    108
fib_Protection      rs.l    1
fib_EntryType       rs.l    1
fib_Size            rs.l    1
fib_NumBlocks       rs.l    1
fib_DateStamp       rs.b    12
fib_Comment         rs.b    80
fib_OwnerUID        rs.w    1
fib_OwnerGID        rs.w    1
fib_Reserved        rs.b    32
fib_SIZEOF          rs.b    0

;
; main
;

start
    move.l  execBase,a6

; open dos.library

    lea     dosName,a1
    moveq   #37,d0
    jsr     _LVOOpenLibrary(a6)
    move.l  d0,dosBase
    beq     exit

; allocate memory for file info block

    move.l  #fib_SIZEOF,d0
    move.l  #MEMF_ANY,d1
    jsr     _LVOAllocVec(a6)
    move.l  d0,fib
    beq     exit

; get directory lock

    move.l  dosBase,a6

    move.l  #pathString,d1
    move.l  #ACCESS_READ,d2
    jsr     _LVOLock(a6)
    move.l  d0,lock
    beq     exit

; examine directory for ExNext

    move.l  lock,d1
    move.l  fib,d2
    jsr     _LVOExamine(a6)
    tst.w   d0
    beq     exit

; parse pattern string

    move.l  #patternString,d1
    move.l  #patternParsed,d2
    move.l  #sizeof_patternString*2+2,d3
    jsr     _LVOParsePatternNoCase(a6)
    tst.l   d0
    blt     exit

; get some pointers for use in the loop

    lea     printfArgs,a2
    move.l  fib,a3
    lea     fib_FileName(a3),a3

.loop

; get next directory entry

    move.l  lock,d1
    move.l  fib,d2
    jsr     _LVOExNext(a6)
    tst.w   d0
    beq     exit

; match pattern

    move.l  #patternParsed,d1
    move.l  a3,d2
    jsr     _LVOMatchPatternNoCase(a6)

; if match then print file name

    tst.l   d0
    beq     .nomatch

    move.l  a3,(a2)
    move.l  #formatString,d1
    move.l  #printfArgs,d2
    jsr     _LVOVPrintf(a6)

.nomatch
    bra     .loop

; cleanup and exit

exit
    move.l  dosBase,a6
    move.l  lock,d1
    jsr     _LVOUnLock(a6)

    move.l  execBase,a6
    move.l  fib,a1
    tst.l   a1
    beq     .l1
    jsr     _LVOFreeVec(a6)
.l1
    move.l  dosBase,a1
    jsr     _LVOCloseLibrary(a6)
    rts

    section data,data_p
;
; variables
;
dosBase
    dc.l    0

lock
    dc.l    0

fib
    dc.l    0

printfArgs
    dc.l    0
;
; strings
;
dosName
    dc.b    "dos.library",0

pathString
    dc.b    "ram:",0

formatString
    dc.b    "%s",10,0

patternString
    dc.b    "#?",0
patternString_end
sizeof_patternString=patternString_end-patternString

patternParsed
    dcb.b   sizeof_patternString*2+2


exit:	equ	0	; CP/M syscall to exit
puts:	equ	9	; CP/M syscall to print a string
sfirst:	equ	17	; 'Find First' CP/M syscall
snext:	equ	18	; 'Find Next' CP/M syscall
FCB:	equ	5Ch	; Location of FCB for file given on command line
	org	100h
	lxi	d,FCB	; CP/M parses the command line for us automatically
	mvi	c,sfirst; and prepares an FCB which we can pass to SFIRST
	call	5	; immediately.
	lxi	d,emsg	; If SFIRST returns an error, there is no file,
	mvi	c,puts	; so we should print an error message.
loop:	inr	a	; A=FF = error
	jz	5
	dcr	a	; If we _do_ have a file, the directory entry
	rrc		; is located at DTA (80h) + A * 32. 0<=A<=3.
	rrc		; Rotate right twice, moving low bits into high bits,
	stc		; then finally rotate a 1 bit into the top bit.
	rar		; The effect is 000000AB -> 1AB00000.
	inr	a	; Finally the filename is at offset 1 in the dirent.
	mvi	h,0	; Set HL = pointer to the filename
	mov	l,a
	lxi	d,fname	; The filename is stored as 'FILENAMEEXT', but let's
	mvi	b,8	; be nice and print 'FILENAME.EXT\r\n'.
	call	memcpy	; Copy filename (wihtout extension) into placeholder
	inx	d	; Skip the '.' in the placeholder
	mvi	b,3	; Then copy the extension
	call	memcpy
	lxi	d,fname	; Then print the formatted filename
	mvi	c,puts
	call	5
	lxi	d,FCB	; Find the next file matching the pattern in the FCB
	mvi	c,snext ; The result is the same as for SFIRST, so we can
	call	5	; loop back here, except FF means no more files.
	mvi	c,exit	; Arrange for the error routine to instead exit cleanly
	jmp	loop
memcpy:	mov	a,m	; Copy B bytes from HL to DE
	stax	d
	inx	h
	inx	d
	dcr 	b
	jnz	memcpy
	ret
emsg:	db	'Not Found$'
fname:	db	'XXXXXXXX.XXX',13,10,'$'	; Filename placeholder


"*.c" f:glob \ puts an array of strings with the file names on the top of the stack


PROC GetFileName(CHAR ARRAY line,fname)
  BYTE i,len

  len=0
  i=3
  FOR i=3 TO 10
  DO
    IF line(i)=32 THEN EXIT FI
    len==+1
    fname(len)=line(i)
  OD
  len==+1
  fname(len)='.
  FOR i=11 TO 13
  DO
    IF line(i)=32 THEN EXIT FI
    len==+1
    fname(len)=line(i)
  OD
  fname(0)=len
RETURN

PROC Dir(CHAR ARRAY filter)
  CHAR ARRAY line(255),fname(255)
  BYTE dev=[1]

  PrintE(filter)
  Close(dev)
  Open(dev,filter,6)
  DO
    InputSD(dev,line)
    IF line(0)=0 OR line(0)>0 AND line(1)#32 THEN
      EXIT
    FI
    GetFileName(line,fname)
    Put(32) PrintE(fname)
  OD
  Close(dev)
  PutE()
RETURN

PROC Main()
  Dir("D:*.*")
  Dir("H1:X*.*")
  Dir("H1:?????.ACT")
  Dir("H1:??F*.*")
RETURN


with Ada.Directories; use Ada.Directories;
with Ada.Text_IO; use Ada.Text_IO;

procedure Walk_Directory
            (Directory : in String := ".";
             Pattern   : in String := "") -- empty pattern = all file names/subdirectory names
is
   Search  : Search_Type;
   Dir_Ent : Directory_Entry_Type;
begin
   Start_Search (Search, Directory, Pattern);

   while More_Entries (Search) loop
      Get_Next_Entry (Search, Dir_Ent);
      Put_Line (Simple_Name (Dir_Ent));
   end loop;

   End_Search (Search);
end Walk_Directory;


INT match=0, no match=1, out of memory error=2, other error=3;

[]STRING directory = get directory(".");
FOR file index TO UPB directory DO
  STRING file = directory[file index];
  IF grep in string("[Ss]ort*.[.]a68$", file, NIL, NIL) = match THEN
    print((file, new line))
  FI
OD


tell application "Finder" to return name of every item in (startup disk)
--> EXAMPLE RESULT: {"Applications", "Developer", "Library", "System", "Users"}


; list all files at current path
print list "."

; get all files at given path
; and select only the ones we want

; just select the files with .md extension
select list "some/path"
    => [".md" = extract.extension]

; just select the files that contain "test"
select list "some/path"
    => [in? "test"]


Loop, %A_WinDir%\*.ini
 out .= A_LoopFileName "`n"
MsgBox,% out


DECLARE SUB show (pattern AS STRING)

show "*.*"

SUB show (pattern AS STRING)
    DIM f AS STRING
    f = DIR$(pattern)
    DO WHILE LEN(f)
        PRINT f
        f = DIR$
    LOOP
END SUB


call show ("c:\")
end

subroutine show (pattern$)
	f$ = dir(pattern$)
	while length(f$)
		print f$
		f$ = dir
	end while
end subroutine


      directory$ = "C:\Windows\"
      pattern$ = "*.ini"
      PROClistdir(directory$ + pattern$)
      END

      DEF PROClistdir(afsp$)
      LOCAL dir%, sh%, res%
      DIM dir% LOCAL 317
      SYS "FindFirstFile", afsp$, dir% TO sh%
      IF sh% <> -1 THEN
        REPEAT
          PRINT $$(dir%+44)
          SYS "FindNextFile", sh%, dir% TO res%
        UNTIL res% = 0
        SYS "FindClose", sh%
      ENDIF
      ENDPROC


#include <sys/types.h>
#include <dirent.h>
#include <regex.h>
#include <stdio.h>

enum {
    WALK_OK = 0,
    WALK_BADPATTERN,
    WALK_BADOPEN,
};

int walker(const char *dir, const char *pattern)
{
    struct dirent *entry;
    regex_t reg;
    DIR *d;

    if (regcomp(&reg, pattern, REG_EXTENDED | REG_NOSUB))
        return WALK_BADPATTERN;
    if (!(d = opendir(dir)))
        return WALK_BADOPEN;
    while (entry = readdir(d))
        if (!regexec(&reg, entry->d_name, 0, NULL, 0))
            puts(entry->d_name);
    closedir(d);
    regfree(&reg);
    return WALK_OK;
}

int main()
{
    walker(".", ".\\.c$");
    return 0;
}


using System;
using System.IO;

namespace DirectoryWalk
{
    class Program
    {
        static void Main(string[] args)
        {
            string[] filePaths = Directory.GetFiles(@"c:\MyDir", "a*");
            foreach (string filename in filePaths)
                Console.WriteLine(filename);
        }
    }
}


#include "boost/filesystem.hpp"
#include "boost/regex.hpp"
#include <iostream>

using namespace boost::filesystem;

int main()
{
  path current_dir(".");
  // list all files starting with a
  boost::regex pattern("a.*");
  for (directory_iterator iter(current_dir), end;
       iter != end;
       ++iter)
  {
    boost::smatch match;
    std::string fn = iter->path().filename().string(); // must make local variable
    if (boost::regex_match( fn, match, pattern))
    {
      std::cout << match[0] << "\n";
    }
  }
}


(import java.nio.file.FileSystems)

(defn match-files [f pattern]
  (.matches (.getPathMatcher (FileSystems/getDefault) (str "glob:*" pattern)) (.toPath f)))

(defn walk-directory [dir pattern]
  (let [directory (clojure.java.io/file dir)]
    (map #(.getPath %) (filter #(match-files % pattern) (.listFiles directory)))))


<cfdirectory action="list" directory="C:\temp" filter="*.html" name="dirListing">
<cfoutput query="dirListing">
  #dirListing.name# (#dirListing.type#)<br>
</cfoutput>


(defun walk-directory (directory pattern)
  (directory (merge-pathnames pattern directory)))


void main() {
    import std.stdio, std.file;

    dirEntries(".", "*.*", SpanMode.shallow).writeln;
}


* matches any number of characters
& matches exactly any one character


program Walk_a_directory;

{$APPTYPE CONSOLE}
{$R *.res}

uses
  System.IOUtils;

var
  Files: TArray<string>;
  FileName, Directory: string;

begin
  Directory := TDirectory.GetCurrentDirectory;  // dir = '.', work to
  Files := TDirectory.GetFiles(Directory, '*.*');

  for FileName in Files do
  begin
    Writeln(FileName);
  end;

  Readln;
end.


def walkDirectory(directory, pattern) {
  for name => file ? (name =~ rx`.*$pattern.*`) in directory {
    println(name)
  }
}


import system'io;
import system'routines;
import extensions'routines;

public program()
{
    var dir := Directory.assign("c:\MyDir");

    dir.getFiles("a.*").forEach:printingLn;
}


# current directory
IO.inspect File.ls!

dir = "/users/public"
IO.inspect File.ls!(dir)


(directory-files "/some/dir/name"
                 nil        ;; just the filenames, not full paths
                 "\\.c\\'"  ;; regexp
                 t)         ;; don't sort the filenames
;;=> ("foo.c" "bar.c" ...)


8> filelib:fold_files( "/tmp", ".*", false, fun(File, Acc) -> [File|Acc] end, []).
["/tmp/.X0-lock","/tmp/.cron-check-4000-was-here",
 "/tmp/kerneloops.XyN0SP","/tmp/npicagwD7tf"]
9> filelib:fold_files( "/tmp", "k.*P", false, fun(File, Acc) -> [File|Acc] end, []).
["/tmp/kerneloops.XyN0SP"]


include file.e

procedure show(sequence pattern)
    sequence f
    f = dir(pattern)
    for i = 1 to length(f) do
        puts(1,f[i][D_NAME])
        puts(1,'\n')
    end for
end procedure

show("*.*")


System.IO.Directory.GetFiles("c:\\temp", "*.xml")
|> Array.iter (printfn "%s")


USING: globs io io.directories kernel regexp sequences ;
IN: walk-directory-non-recursively

: print-files ( path pattern -- )
    [ directory-files ] [ <glob> ] bi* [ matches? ] curry filter
    [ print ] each ;


defer ls-filter ( name len -- ? )
: ls-all  2drop true ;
: ls-visible  drop [email protected] [char] . <> ;

: ls ( dir len -- )
  open-dir throw  ( dirid )
  begin
    dup pad 256 rot read-dir throw
  while
    pad over ls-filter if
      cr pad swap type
    else drop then
  repeat
  drop close-dir throw ;

\ only show C language source and header files (*.c *.h)
: c-file? ( str len -- ? )
  dup 3 < if 2drop false exit then
  + 1- dup [email protected]
   dup [char] c <> swap [char] h <> and if drop false exit then
  1- dup [email protected] [char] . <> if drop false exit then
  drop true ;
' c-file? is ls-filter

s" ." ls


Sub show (pattern As String)
    Dim As String f = Dir$(pattern)
    While Len(f)
        Print f
        f = Dir$
    Wend
End Sub

show "*.*"
Sleep


for f = select[files["."], {|f1| f1.getName[] =~ %r/\.frink$/}]
   println[f.getName[]]


Public Sub Main()
Dim sTemp As String

For Each sTemp In Dir("/etc", "*.d")
  Print sTemp
Next

End


package main

import (
    "fmt"
    "path/filepath"
)

func main() {
    fmt.Println(filepath.Glob("*.go"))
}


// *** print *.txt files in current directory
 new File('.').eachFileMatch(~/.*\.txt/) {
   println it
 }

 // *** print *.txt files in /foo/bar
 new File('/foo/bar').eachFileMatch(~/.*\.txt/) {
   println it
 }


use fmt;
use glob;

export fn main() void = {
	ls("/etc/*.conf");
};

fn ls(pattern: str) void = {
	let gen = glob::glob(pattern, glob::flags::NONE);
	defer glob::finish(&gen);
	for (true) match (glob::next(&gen)) {
	case void =>
		break;
	case glob::failure =>
		continue;
	case let s: str =>
		fmt::printfln("{}", s)!;
	};
};


import System.Directory
import Text.Regex
import Data.Maybe

walk :: FilePath -> String -> IO ()
walk dir pattern = do
    filenames <- getDirectoryContents dir
    mapM_ putStrLn $ filter (isJust.(matchRegex $ mkRegex pattern)) filenames

main = walk "." ".\\.hs$"


CHARACTER dirtxt='dir.txt', filename*80

SYSTEM(DIR='*.*', FIle=dirtxt) ! "file names", length, attrib, Created, LastWrite, LastAccess
OPEN(FIle=dirtxt, Format='"",', LENgth=files) ! parses column 1 ("file names")

DO nr = 1, files
  filename = dirtxt(nr,1) ! reads dirtxt row = nr, column = 1 to filename
  ! write file names with extensions "txt", or "hic", or "jpg" (case insensitive) using RegEx option =128:
  IF( INDEX(filename, "\.txt|\.hic|\.jpg", 128) ) WRITE() filename
ENDDO


procedure main()
every write(getdirs(".","icn"))  # writes out all directories from the current directory down
end

procedure getdirs(s,pat)  #: return a list of directories beneath the directory 's'
local d,f

if ( stat(s).mode ? ="d" ) & ( d := open(s) ) then {
      while f := read(d) do
         if find(pat,f) then
            suspend f
      close(d)
      }
end


f = file_search('*.txt', count=cc)
if cc gt 0 then print,f


require 'dir'
0 dir '*.png'
0 dir '/mydir/*.txt'


File dir = new File("/foo/bar");

String[] contents = dir.list();
for (String file : contents)
    if (file.endsWith(".mp3"))
        System.out.println(file);


var fso = new ActiveXObject("Scripting.FileSystemObject");
var dir = fso.GetFolder('test_folder');

function walkDirectory(dir, re_pattern) {
    WScript.Echo("Files in " + dir.name + " matching '" + re_pattern +"':");
    walkDirectoryFilter(dir.Files, re_pattern);

    WScript.Echo("Folders in " + dir.name + " matching '" + re_pattern +"':");
    walkDirectoryFilter(dir.Subfolders, re_pattern);
}

function walkDirectoryFilter(items, re_pattern) {
    var e = new Enumerator(items);
    while (! e.atEnd()) {
        var item = e.item();
        if (item.name.match(re_pattern))
            WScript.Echo(item.name);
        e.moveNext();
    }
}

walkDirectory(dir, '\\.txt$');


for filename in readdir("/foo/bar")
    if endswith(filename, ".mp3")
        print(filename)
    end
end


// version 1.1.2

import java.io.File

fun walkDirectory(dirPath: String, pattern: Regex): List<String> {
    val d = File(dirPath)
    require(d.exists() && d.isDirectory())
    return d.list().filter { it.matches(pattern) }
}

fun main(args: Array<String>) {
    val r = Regex("""^a.*\.h$""")  // get all C header files beginning with 'a'
    val files = walkDirectory("/usr/include", r)
    for (file in files) println(file)
}


local(matchingfilenames = array)

dir('.') -> foreach => {#1 >> 'string' ? #matchingfilenames -> insert(#1)}

#matchingfilenames


-- Usage: printFiles("C:\scripts", ".ls")
on printFiles (dir, fileType)
  i = 1
  sub = fileType.length -1
  repeat while TRUE
    fn = getNthFileNameInFolder(dir, i)
    if fn = EMPTY then exit repeat
    i = i+1
    if fn.length<fileType.length then next repeat
    if fn.char[fn.length-sub..fn.length]=fileType then put fn
  end repeat
end


set the defaultFolder to the documents folder  -- the documents folder is a "specialFolderPath"
put the files into docfiles
filter docfiles with "*.txt"
put docfiles


require "lfs"
directorypath = "." -- current working directory
for filename in lfs.dir(directorypath) do
    if filename:match("%.lua$") then -- "%." is an escaped ".", "$" is end of string
        print(filename)
    end
end


Module Show_Files_Standard {
      \\ we get more (include hidden too)
      Module InnerWay (folder_path$, pattern$){
            olddir$=dir$
            dir folder_path$
            \\ clear menu list
            Menu
            \\ + place export to menu, without showing
            \\ ! sort to name
            files ! + pattern$
            If MenuItems>0 then {
                  For i=1 to MenuItems {
                        Print Menu$(i)+".exe"
                  }
            }
            dir olddir$
      }
      InnerWay "C:\Windows","*.exe"
}
Show_Files_Standard


        TITLE  DIRWLK - Directory Walker
        SUBTTL PDP-10 Assembly Language (MACRO-10 @ TOPS-20). KJX 2022.

        SEARCH MONSYM,MACSYM            ;Get system-call names.
        .REQUIRE SYS:MACREL             ;Macros: TMSG, EJSHLT, etc.

        STDAC.                          ;Define standard register names.

JFN:    BLOCK 1                         ;Space for JFN (file-handle)
FSPEC:  BLOCK 20                        ;Space for file specification.
FSPECL= <.-FSPEC>*5                     ;Length in chars of file-spec.

GO::    RESET%                          ;Initialize process.
        TMSG <Please enter filespec, wildcards are allowed: >
        HRROI T1,FSPEC                  ;Read into FSPEC.
        MOVEI T2,FSPECL                 ;Maximum allowed characters.
        SETZ  T3,                       ;No Ctrl-R prompting.
        RDTTY%                          ;Read string from terminal.
          EJSHLT                        ;  Print error-msg on errors.

        MOVX  T1,GJ%OLD!GJ%IFG!GJ%FLG!GJ%SHT  ;Various flags.
        HRROI T2,FSPEC                  ;File specification from above.
        GTJFN%                          ;Get JFN for first matching file.
          EJSHLT                        ;  Print error-msg on errors.
        MOVEM T1,JFN                    ;Save JFN.

        DO.
          MOVEI T1,.PRIOU               ;Write to standard-output.
          HRRZ  T2,JFN                  ;JFN from above to decode.
          SETZ  T3,                     ;No flags.
          JFNS%                         ;Decode filename and print it.
            EJSHLT                      ;  Print error-msg on errors.
          TMSG <
>                                       ;Print newline.
          MOVE  T1,JFN                  ;Get JFN into T1.
          GNJFN%                        ;Get next matching file.
            JRST [ HALTF%               ;  Halt program on failure.
                   JRST GO ]
          LOOP.                         ;No error: Do it again.
        ENDDO.

        END GO


import Nanoquery.IO

for fname in new(File).listDir("/foo/bar")
	if lower(new(File, fname).getExtension()) = ".mp3"
		println filename
	end
end


using System.Console;
using System.IO;

module DirWalk
{
    Main() : void
    {
        def files = Directory.GetFiles(@"C:\MyDir");                  // retrieves only files
        def files_subs = Directory.GetFileSystemEntries(@"C:\MyDir"); // also retrieves (but does not enter) sub-directories
                                                                      // (like ls command)
        foreach (file in files) WriteLine(file);
    }
}


/* NetRexx */
options replace format comments java crossref symbols nobinary

import java.util.List

runSample(arg)
return

-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
method getFileNames(dirname, pattern) public static returns List
  dir = File(dirname)
  contents = dir.list()
  fileNames = ArrayList()
  loop fname over contents
    if fname.matches(pattern) then do
      fileNames.add(fname)
      end
    end fname
  Collections.sort(fileNames)
  return fileNames

-- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
method runSample(arg) private static
  parse arg dirname pattern
  if dirname = '' then dirname = System.getProperty('user.dir')
  if pattern = '' then pattern = '^RW.*\\.nrx$'

  fileNames = getFileNames(dirname, pattern)
  say 'Search of' dirname 'for files matching pattern "'pattern'" found' fileNames.size() 'files.'
  loop fn = 0 while fn < fileNames.size()
    say (fn + 1).right(5)':' fileNames.get(fn)
    end fn

  return


import os

for file in walkFiles "/foo/bar/*.mp3":
  echo file


use IO;

bundle Default {
  class Test {
    function : Main(args : System.String[]) ~ Nil {
       dir := Directory->List("/src/code");
       for(i := 0; i < dir->Size(); i += 1;) {
         if(dir[i]->EndsWith(".obs")) {
           dir[i]->PrintLine();
        };
      };
    }
  }
}


NSString *dir = @"/foo/bar";

// Pre-OS X 10.5
NSArray *contents = [[NSFileManager defaultManager] directoryContentsAtPath:dir];
// OS X 10.5+
NSArray *contents = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:dir error:NULL];

for (NSString *file in contents)
  if ([[file pathExtension] isEqualToString:@"mp3"])
    NSLog(@"%@", file);


#load "str.cma"
let contents = Array.to_list (Sys.readdir ".") in
let select pat str = Str.string_match (Str.regexp pat) str 0 in
List.filter (select ".*\\.jpg") contents


declare
  [Path] = {Module.link ['x-oz://system/os/Path.ozf']}
  [Regex] = {Module.link ['x-oz://contrib/regex']}

  Files = {Filter {Path.readdir "."} Path.isFile}
  Pattern = ".*\\.oz$"
  MatchingFiles = {Filter Files fun {$ File} {Regex.search Pattern File} \= false end}
in
  {ForAll MatchingFiles System.showInfo}


{$H+}

program Walk;

uses SysUtils;

var Res: TSearchRec;
    Pattern, Path, Name: String;
    FileAttr: LongInt;
    Attr: Integer;

begin
   Write('File pattern: ');
   ReadLn(Pattern);            { For example .\*.pas }

   Attr := faAnyFile;
   if FindFirst(Pattern, Attr, Res) = 0 then
   begin
      Path := ExtractFileDir(Pattern);
      repeat
         Name := ConcatPaths([Path, Res.Name]);
         FileAttr := FileGetAttr(Name);
         if FileAttr and faDirectory = 0 then
         begin
            { Do something with file name }
            WriteLn(Name);
         end
      until FindNext(Res) <> 0;
   end;
   FindClose(Res);
end.


use 5.010;
opendir my $dh, '/home/foo/bar';
say for grep { /php$/ } readdir $dh;
closedir $dh;


$pattern = 'php';
$dh = opendir('c:/foo/bar'); // Or '/home/foo/bar' for Linux
while (false !== ($file = readdir($dh)))
{
    if ($file != '.' and $file != '..')
    {
        if (preg_match("/$pattern/", $file))
        {
            echo "$file matches $pattern\n";
        }
    }
}
closedir($dh);


(for F (dir "@src/")                         # Iterate directory
   (when (match '`(chop "[email protected]") (chop F))    # Matches 's*.c'?
      (println F) ) )                        # Yes: Print it


array(string) files = get_dir("/home/foo/bar");
foreach(files, string file)
    write(file + "\n");


lvars repp, fil;
;;; create path repeater
sys_file_match('*.p', '', false, 0) -> repp;
;;; iterate over files
while (repp() ->> fil) /= termin do
     ;;; print the file
     printf(fil, '%s\n');
endwhile;


Get-ChildItem *.txt -Name
Get-ChildItem f* -Name


Procedure walkDirectory(directory.s = "", pattern.s = "")
  Protected directoryID

  directoryID = ExamineDirectory(#PB_Any,directory,pattern)
  If directoryID
    While NextDirectoryEntry(directoryID)
      PrintN(DirectoryEntryName(directoryID))
    Wend
    FinishDirectory(directoryID)
  EndIf
EndProcedure

If OpenConsole()
  walkDirectory()

  Print(#CRLF$ + #CRLF$ + "Press ENTER to exit")
  Input()
  CloseConsole()
EndIf


import glob
for filename in glob.glob('/foo/bar/*.mp3'):
    print(filename)


-> (for ([f (directory-list "/tmp")] #:when (regexp-match? "\\.rkt$" f))
     (displayln f))
... *.rkt files ...


import IO;
public void Walk(loc a, str pattern){
	for (entry <- listEntries(a))
		endsWith(entry, pattern) ? println(entry);
}


'dir://.' open each as item
    item m/\.txt$/ if "%(item)s\n" print


/*REXX program shows files in directory tree that match a given criteria*/
parse arg xdir;  if xdir='' then xdir='\'        /*Any DIR? Use default.*/
@.=0                                   /*default in case ADDRESS fails. */
trace off                              /*suppress REXX err msg for fails*/
address system 'DIR' xdir '/b /s' with output stem @.   /*issue DIR cmd.*/
if rc\==0  then do                                  /*an error happened?*/
                say '***error!*** from DIR' xDIR    /*indicate que pasa.*/
                say 'return code='  rc              /*show the Ret Code.*/
                exit rc                             /*exit with the  RC.*/
                end                                 /* [↑]  bad address.*/
#[email protected].rc                                              /*number of entries.*/
if #==0  then #='   no   '                          /*use a word, ¬zero.*/
say center('directory ' xdir " has "    #     ' matching entries.',79,'─')

       do j=1  for #;  say @.j;  end   /*show files that met criteria.  */

exit @.0+rc                            /*stick a fork in it, we're done.*/


###---------------------------------------
### Directory Tree Walk
### Look for FileType for Music and Video

fileType = [".avi", ".mp4", ".mpg", ".mkv", ".mp3", ".wmv" ]

dirList   = []
musicList = []

###---------------------------------------
### Main

    ###-----------------------------------
    ### Start at this directory

    searchVideoMusic("C:\Users\Umberto\")

    see nl +"Number of Music and Videos files: " +len(musicList) +nl +nl
    see musicList
    See nl +"Finished" +nl

###=======================================
### Search for Video and Music files

Func searchVideoMusic(startDir)

    ChDir(startDir + "Music")     ### <<<== add Music subpath C:\Users\Umberto\Music
    listDir( CurrentDir() )

    ChDir(startDir + "Videos")    ### <<<== add Videos subpath C:\Users\Umberto\Videos
    listDir( CurrentDir() )

    for searchDir in dirList      ### Search Directory List for Music and Videos files
        listDir(searchDir)
    next

###==============================
### Find Files in Directory

Func listDir(dirName)

    ChDir(dirName)
    Try
        ###-------------------------------------
        ### Get SubDirectories

        myListSub = Dir( CurrentDir() )
    Catch
        ###-------------------------------------
        ### Error, Couldn't open the directory

        See "ListDir Catch! " + CurrentDir() +" --- "+ cCatchError +nl
        return
    Done

    for x in myListSub
        if x[2]
            thisDir = x[1]

            if thisDir[1] = "."
                ### Do Nothing. Ignore dot.name

            else
                see nl +"Dir: " + CurrentDir() +"\"+ thisDir + nl

                ###----------------------------------------
                ###  Directory Walk add to directory list

                Add( dirList, (CurrentDir() +"\"+  thisDir))
            ok
        else
            thisFile = x[1]

            ###-------------------------------
            ### Add Music or Video file type

            for thisType in fileType
                if ( substr(thisFile, thisType) )             ### <<<== Type of File from List
                     see "         File: " + thisFile + nl
                     Add(musicList, (CurrentDir() +"\"+  thisFile))
                ok
            next
        ok
    next
return

###===============================================


# Files under this directory:
Dir.glob('*') { |file| puts file }

# Files under path '/foo/bar':
Dir.glob( File.join('/foo/bar', '*') ) { |file| puts file }

# As a method
def file_match(pattern=/\.txt/, path='.')
  Dir[File.join(path,'*')].each do |file|
    puts file if file =~ pattern
  end
end


files #g, DefaultDir$ + "\*.jpg"   ' find all jpg files

if #g HASANSWER() then
	count = #g rowcount()	' get count of files
	for i = 1 to count
	if #g hasanswer() then	'retrieve info for next file
		#g nextfile$()	'print name of file
		print #g NAME$()
	end if
	next
end if
wait


extern crate docopt;
extern crate regex;
extern crate rustc_serialize;

use docopt::Docopt;
use regex::Regex;

const USAGE: &'static str = "
Usage: rosetta <pattern>

Walks the directory tree starting with the current working directory and
print filenames matching <pattern>.
";

#[derive(Debug, RustcDecodable)]
struct Args {
    arg_pattern: String,
}

fn main() {
    let args: Args = Docopt::new(USAGE)
        .and_then(|d| d.decode())
        .unwrap_or_else(|e| e.exit());

    let re = Regex::new(&args.arg_pattern).unwrap();
    let paths = std::fs::read_dir(".").unwrap();

    for path in paths {
        let path = path.unwrap().path();
        let path = path.to_str().unwrap();

        if re.is_match(path) {
            println!("{}", path);
        }
    }
}


import java.io.File

val dir = new File("/foo/bar").list()
dir.filter(file => file.endsWith(".mp3")).foreach(println)


$ include "seed7_05.s7i";
  include "osfiles.s7i";

const proc: main is func
  local
    var string: fileName is "";
  begin
    for fileName range readDir(".") do
      if endsWith(fileName, ".sd7") then
        writeln(fileName);
      end if;
    end for;
  end func;


'*.p[lm]'.glob.each { |file| say file }    # Perl files under this directory


(Directory name: 'a_directory')
  allFilesMatching: '*.st' do: [ :f | (f name) displayNl ]


fun dirEntries path =
  let
    fun loop strm =
      case OS.FileSys.readDir strm of
        SOME name => name :: loop strm
      | NONE => []
    val strm = OS.FileSys.openDir path
  in
    loop strm before OS.FileSys.closeDir strm
  end


foreach filename [glob *.txt] {
    puts $filename
}


needs shell
" ."  " .\\.txt$" dir.listByPattern


$$ MODE TUSCRIPT
files=FILE_NAMES (+,-std-)
fileswtxt= FILTER_INDEX (files,":*.txt:",-)
txtfiles= SELECT (files,#fileswtxt)


ls -d *.c                # *.c files in current directory
(cd mydir && ls -d *.c)  # *.c files in mydir


Sub show_files(folder_path,pattern)
	Set objfso = CreateObject("Scripting.FileSystemObject")
	For Each file In objfso.GetFolder(folder_path).Files
		If InStr(file.Name,pattern) Then
			WScript.StdOut.WriteLine file.Name
		End If
	Next
End Sub

Call show_files("C:\Windows",".exe")


'Using the OS pattern matching
For Each file In IO.Directory.GetFiles("\temp", "*.txt")
  Console.WriteLine(file)
Next

'Using VB's pattern matching and LINQ
For Each file In (From name In IO.Directory.GetFiles("\temp") Where name Like "*.txt")
  Console.WriteLine(file)
Next

'Using VB's pattern matching and dot-notation
For Each file In IO.Directory.GetFiles("\temp").Where(Function(f) f Like "*.txt")
  Console.WriteLine(file)
Next


import "io" for Directory
import "/pattern" for Pattern

var walk = Fn.new { |dir, pattern|
    if (!Directory.exists(dir)) Fiber.abort("Directory does not exist.")
    var files = Directory.list(dir)
    return files.where { |f| pattern.isMatch(f) }
}

// get all C header files beginning with 'a' or 'b'
var p = Pattern.new("[a|b]+0^..h", Pattern.whole)
for (f in walk.call("/usr/include", p)) System.print(f)


File.glob("*.zkl") //--> list of matches


-V ascii_uppercase = Array(‘A’..‘Z’)

F vigenere_decrypt(target_freqs, input)
   V nchars = :ascii_uppercase.len
   V ordA = ‘A’.code
   V sorted_targets = sorted(target_freqs)

   F frequency(input)
      V result = :ascii_uppercase.map(c -> (c, 0.0))
      L(c) input
         result[c - @ordA][1]++
      R result

   F correlation(input)
      V result = 0.0
      V freq = sorted(@frequency(input), key' a -> a[1])

      L(f) freq
         result += f[1] * @sorted_targets[L.index]
      R result

   V cleaned = input.uppercase().filter(c -> c.is_uppercase()).map(c -> c.code)
   V best_len = 0
   V best_corr = -100.0

   L(i) 2 .< cleaned.len I/ 20
      V pieces = [[Int]()] * i
      L(c) cleaned
         pieces[L.index % i].append(c)
      V corr = -0.5 * i + sum(pieces.map(p -> @correlation(p)))

      I corr > best_corr
         best_len = i
         best_corr = corr

   I best_len == 0
      R (‘Text is too short to analyze’, ‘’)

   V pieces = [[Int]()] * best_len
   L(c) cleaned
      pieces[L.index % best_len].append(c)

   V freqs = pieces.map(p -> @frequency(p))

   V key = ‘’
   L(fr_) freqs
      V fr = sorted(fr_, key' a -> a[1], reverse' 1B)
      V m = 0
      V max_corr = 0.0
      L(j) 0 .< nchars
         V corr = 0.0
         V c = ordA + j
         L(frc) fr
            V d = (frc[0].code - c + nchars) % nchars
            corr += frc[1] * target_freqs[d]

         I corr > max_corr
            m = j
            max_corr = corr

      key ‘’= Char(code' m + ordA)

   V r = (enumerate(cleaned).map((i, c) -> Char(code' (c - @key[i % @best_len].code + @nchars) % @nchars + @ordA)))
   R (key, r.join(‘’))

V encoded = ‘
    MOMUD EKAPV TQEFM OEVHP AJMII CDCTI FGYAG JSPXY ALUYM NSMYH
    VUXJE LEPXJ FXGCM JHKDZ RYICU HYPUS PGIGM OIYHF WHTCQ KMLRD
    ITLXZ LJFVQ GHOLW CUHLO MDSOE KTALU VYLNZ RFGBX PHVGA LWQIS
    FGRPH JOOFW GUBYI LAPLA LCAFA AMKLG CETDW VOELJ IKGJB XPHVG
    ALWQC SNWBU BYHCU HKOCE XJEYK BQKVY KIIEH GRLGH XEOLW AWFOJ
    ILOVV RHPKD WIHKN ATUHN VRYAQ DIVHX FHRZV QWMWV LGSHN NLVZS
    JLAKI FHXUF XJLXM TBLQV RXXHR FZXGV LRAJI EXPRV OSMNP KEPDT
    LPRWM JAZPK LQUZA ALGZX GVLKL GJTUI ITDSU REZXJ ERXZS HMPST
    MTEOE PAPJH SMFNB YVQUZ AALGA YDNMP AQOWT UHDBV TSMUE UIMVH
    QGVRW AEFSP EMPVE PKXZY WLKJA GWALT VYYOB YIXOK IHPDS EVLEV
    RVSGB JOGYW FHKBL GLXYA MVKIS KIEHY IMAPX UOISK PVAGN MZHPW
    TTZPV XFCCD TUHJH WLAPF YULTB UXJLN SIJVV YOVDJ SOLXG TGRVO
    SFRII CTMKO JFCQF KTINQ BWVHG TENLH HOGCS PSFPV GJOKM SIFPR
    ZPAAS ATPTZ FTPPD PORRF TAXZP KALQA WMIUD BWNCT LEFKO ZQDLX
    BUXJL ASIMR PNMBF ZCYLV WAPVF QRHZV ZGZEF KBYIO OFXYE VOWGB
    BXVCB XBAWG LQKCM ICRRX MACUO IKHQU AJEGL OIJHH XPVZW JEWBA
    FWAML ZZRXJ EKAHV FASMU LVVUT TGK’

V english_frequences = [
   0.08167, 0.01492, 0.02782, 0.04253, 0.12702, 0.02228, 0.02015,
   0.06094, 0.06966, 0.00153, 0.00772, 0.04025, 0.02406, 0.06749,
   0.07507, 0.01929, 0.00095, 0.05987, 0.06327, 0.09056, 0.02758,
   0.00978, 0.02360, 0.00150, 0.01974, 0.00074]

V (key, decoded) = vigenere_decrypt(english_frequences, encoded)
print(‘Key: ’key)
print("\nText: "decoded)


with Ada.Text_IO;

procedure Vignere_Cryptanalysis is

   subtype Letter is Character range 'A' .. 'Z';

   function "+"(X, Y: Letter) return Letter is
   begin
      return Character'Val( ( (Character'Pos(X)-Character'Pos('A'))
                                + (Character'Pos(Y)-Character'Pos('A')) ) mod 26
                          + Character'Pos('A'));
   end;

   function "-"(X, Y: Letter) return Letter is
   begin
      return Character'Val( ( (Character'Pos(X)-Character'Pos('A'))
                                - (Character'Pos(Y)-Character'Pos('A')) ) mod 26
                          + Character'Pos('A'));
   end;

   type Frequency_Array is array (Letter) of Float;

   English: Frequency_Array :=
     ( 0.08167, 0.01492, 0.02782, 0.04253, 0.12702, 0.02228, 0.02015,
       0.06094, 0.06966, 0.00153, 0.00772, 0.04025, 0.02406, 0.06749,
       0.07507, 0.01929, 0.00095, 0.05987, 0.06327, 0.09056, 0.02758,
       0.00978, 0.02360, 0.00150, 0.01974, 0.00074 );

   function Get_Frequency(S: String) return Frequency_Array is
      Result: Frequency_Array := (others => 0.0);
      Offset: Float := 1.0/Float(S'Length);
   begin
      for I in S'Range loop
         if S(I) in Letter then
            Result(S(I)) := Result(S(I)) + Offset;
         end if;
      end loop;
      return Result;
   end Get_Frequency;

   function Remove_Whitespace(S: String) return String is
   begin
      if S="" then
         return "";
      elsif S(S'First) in Letter then
         return S(S'First) & Remove_Whitespace(S(S'First+1 .. S'Last));
      else
         return Remove_Whitespace(S(S'First+1 .. S'Last));
      end if;
   end Remove_Whitespace;

   function Distance(A, B: Frequency_Array;
                     Offset: Character := 'A') return Float is
      Result: Float := 0.0;
      Diff: Float;
   begin
      for C in A'Range loop
         Diff := A(C+Offset) - B(C);
         Result := Result + (Diff * Diff);
      end loop;
      return Result;
   end Distance;

   function Find_Key(Cryptogram: String; Key_Length: Positive) return String is

      function Find_Caesar_Key(S: String) return Letter is
         Frequency: Frequency_Array := Get_Frequency(S);
         Candidate: Letter := 'A'; -- a fake candidate
         Candidate_Dist : Float := Distance(Frequency, English, 'A');
         New_Dist: Float;

      begin

         for L in Letter range 'B' .. 'Z' loop
            New_Dist := Distance(Frequency, English, L);
            if New_Dist <= Candidate_Dist then
               Candidate_Dist := New_Dist;
               Candidate      := L;
            end if;
         end loop;
         return Candidate;
      end Find_Caesar_Key;

      function Get_Slide(S: String; Step: Positive) return String is
      begin
         if S'Length= 0 then
            return "";
         else
            return S(S'First) & Get_Slide(S(S'First+Step .. S'Last), Step);
         end if;
      end Get_Slide;

      Key: String(1 .. Key_Length);

      S: String renames Cryptogram;

   begin
      for I in Key'Range loop
         Key(I) := Find_Caesar_Key(Get_Slide(S(S'First+I-1 .. S'Last),
                                             Key_Length));
      end loop;
      return Key;
   end Find_Key;

   function Key_Char(Key: String; Index: Positive) return Letter is
   begin
      if Index > Key'Last then
         return Key_Char(Key, Index-Key'Last);
      else
         return Key(Index);
      end if;
   end Key_Char;

   Ciphertext: String := Remove_Whitespace(
     "MOMUD EKAPV TQEFM OEVHP AJMII CDCTI FGYAG JSPXY ALUYM NSMYH" &
     "VUXJE LEPXJ FXGCM JHKDZ RYICU HYPUS PGIGM OIYHF WHTCQ KMLRD" &
     "ITLXZ LJFVQ GHOLW CUHLO MDSOE KTALU VYLNZ RFGBX PHVGA LWQIS" &
     "FGRPH JOOFW GUBYI LAPLA LCAFA AMKLG CETDW VOELJ IKGJB XPHVG" &
     "ALWQC SNWBU BYHCU HKOCE XJEYK BQKVY KIIEH GRLGH XEOLW AWFOJ" &
     "ILOVV RHPKD WIHKN ATUHN VRYAQ DIVHX FHRZV QWMWV LGSHN NLVZS" &
     "JLAKI FHXUF XJLXM TBLQV RXXHR FZXGV LRAJI EXPRV OSMNP KEPDT" &
     "LPRWM JAZPK LQUZA ALGZX GVLKL GJTUI ITDSU REZXJ ERXZS HMPST" &
     "MTEOE PAPJH SMFNB YVQUZ AALGA YDNMP AQOWT UHDBV TSMUE UIMVH" &
     "QGVRW AEFSP EMPVE PKXZY WLKJA GWALT VYYOB YIXOK IHPDS EVLEV" &
     "RVSGB JOGYW FHKBL GLXYA MVKIS KIEHY IMAPX UOISK PVAGN MZHPW" &
     "TTZPV XFCCD TUHJH WLAPF YULTB UXJLN SIJVV YOVDJ SOLXG TGRVO" &
     "SFRII CTMKO JFCQF KTINQ BWVHG TENLH HOGCS PSFPV GJOKM SIFPR" &
     "ZPAAS ATPTZ FTPPD PORRF TAXZP KALQA WMIUD BWNCT LEFKO ZQDLX" &
     "BUXJL ASIMR PNMBF ZCYLV WAPVF QRHZV ZGZEF KBYIO OFXYE VOWGB" &
     "BXVCB XBAWG LQKCM ICRRX MACUO IKHQU AJEGL OIJHH XPVZW JEWBA" &
     "FWAML ZZRXJ EKAHV FASMU LVVUT TGK");

   Best_Plain: String := Ciphertext;
   Best_Dist:  Float := Distance(English, Get_Frequency(Best_Plain));
   Best_Key:   String := Ciphertext;
   Best_Key_L: Natural := 0;

begin -- Vignere_Cryptanalysis
   for I in 1 .. Ciphertext'Length/10 loop
      declare
         Key: String(1 .. I) := Find_Key(Ciphertext, I);
         Plaintext: String(Ciphertext'Range);
      begin
         for I in Ciphertext'Range loop
            Plaintext(I) := Ciphertext(I) - Key_Char(Key, I);
         end loop;
         if Distance(English, Get_Frequency(Plaintext)) < Best_Dist then
            Best_Plain := Plaintext;
            Best_Dist  := Distance(English, Get_Frequency(Plaintext));
            Best_Key(1 .. I) := Key;
            Best_Key_L := I;
            if Best_dist < 0.01 then
               declare
                  use Ada.Text_IO;
               begin
                  Put_Line("Key       =" & Best_Key(1 .. Best_Key_L));
                  Put_Line("Distance = " & Float'Image(Best_Dist));
                  New_Line;
                  Put_Line("Plaintext =");
                  Put_Line(Best_Plain);
                  New_Line; New_Line;
               end;
            end if;
         end if;
      end;
   end loop;
end Vignere_Cryptanalysis;


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

const char *encoded =
    "MOMUD EKAPV TQEFM OEVHP AJMII CDCTI FGYAG JSPXY ALUYM NSMYH"
    "VUXJE LEPXJ FXGCM JHKDZ RYICU HYPUS PGIGM OIYHF WHTCQ KMLRD"
    "ITLXZ LJFVQ GHOLW CUHLO MDSOE KTALU VYLNZ RFGBX PHVGA LWQIS"
    "FGRPH JOOFW GUBYI LAPLA LCAFA AMKLG CETDW VOELJ IKGJB XPHVG"
    "ALWQC SNWBU BYHCU HKOCE XJEYK BQKVY KIIEH GRLGH XEOLW AWFOJ"
    "ILOVV RHPKD WIHKN ATUHN VRYAQ DIVHX FHRZV QWMWV LGSHN NLVZS"
    "JLAKI FHXUF XJLXM TBLQV RXXHR FZXGV LRAJI EXPRV OSMNP KEPDT"
    "LPRWM JAZPK LQUZA ALGZX GVLKL GJTUI ITDSU REZXJ ERXZS HMPST"
    "MTEOE PAPJH SMFNB YVQUZ AALGA YDNMP AQOWT UHDBV TSMUE UIMVH"
    "QGVRW AEFSP EMPVE PKXZY WLKJA GWALT VYYOB YIXOK IHPDS EVLEV"
    "RVSGB JOGYW FHKBL GLXYA MVKIS KIEHY IMAPX UOISK PVAGN MZHPW"
    "TTZPV XFCCD TUHJH WLAPF YULTB UXJLN SIJVV YOVDJ SOLXG TGRVO"
    "SFRII CTMKO JFCQF KTINQ BWVHG TENLH HOGCS PSFPV GJOKM SIFPR"
    "ZPAAS ATPTZ FTPPD PORRF TAXZP KALQA WMIUD BWNCT LEFKO ZQDLX"
    "BUXJL ASIMR PNMBF ZCYLV WAPVF QRHZV ZGZEF KBYIO OFXYE VOWGB"
    "BXVCB XBAWG LQKCM ICRRX MACUO IKHQU AJEGL OIJHH XPVZW JEWBA"
    "FWAML ZZRXJ EKAHV FASMU LVVUT TGK";

const double freq[] = {
    0.08167, 0.01492, 0.02782, 0.04253, 0.12702, 0.02228, 0.02015,
    0.06094, 0.06966, 0.00153, 0.00772, 0.04025, 0.02406, 0.06749,
    0.07507, 0.01929, 0.00095, 0.05987, 0.06327, 0.09056, 0.02758,
    0.00978, 0.02360, 0.00150, 0.01974, 0.00074
};

int best_match(const double *a, const double *b) {
    double sum = 0, fit, d, best_fit = 1e100;
    int i, rotate, best_rotate = 0;
    for (i = 0; i < 26; i++)
        sum += a[i];
    for (rotate = 0; rotate < 26; rotate++) {
        fit = 0;
        for (i = 0; i < 26; i++) {
            d = a[(i + rotate) % 26] / sum - b[i];
            fit += d * d / b[i];
        }

        if (fit < best_fit) {
            best_fit = fit;
            best_rotate = rotate;
        }
    }

    return best_rotate;
}

double freq_every_nth(const int *msg, int len, int interval, char *key) {
    double sum, d, ret;
    double out[26], accu[26] = {0};
    int i, j, rot;

    for (j = 0; j < interval; j++) {
        for (i = 0; i < 26; i++)
            out[i] = 0;
        for (i = j; i < len; i += interval)
            out[msg[i]]++;
        key[j] = rot = best_match(out, freq);
        key[j] += 'A';
        for (i = 0; i < 26; i++)
            accu[i] += out[(i + rot) % 26];
    }

    for (i = 0, sum = 0; i < 26; i++)
        sum += accu[i];

    for (i = 0, ret = 0; i < 26; i++) {
        d = accu[i] / sum - freq[i];
        ret += d * d / freq[i];
    }

    key[interval] = '\0';
    return ret;
}

int main() {
    int txt[strlen(encoded)];
    int len = 0, j;
    char key[100];
    double fit, best_fit = 1e100;

    for (j = 0; encoded[j] != '\0'; j++)
        if (isupper(encoded[j]))
            txt[len++] = encoded[j] - 'A';

    for (j = 1; j < 30; j++) {
        fit = freq_every_nth(txt, len, j, key);
        printf("%f, key length: %2d, %s", fit, j, key);
        if (fit < best_fit) {
            best_fit = fit;
            printf(" <--- best so far");
        }
        printf("\n");
    }

    return 0;
}


#include <iostream>
#include <string>
#include <vector>
#include <map>
#include <algorithm>
#include <array>
using namespace std;

typedef array<pair<char, double>, 26> FreqArray;

class VigenereAnalyser
{
private:
  array<double, 26> targets;
  array<double, 26> sortedTargets;
  FreqArray freq;

  // Update the freqs array
  FreqArray& frequency(const string& input)
  {
    for (char c = 'A'; c <= 'Z'; ++c)
      freq[c - 'A'] = make_pair(c, 0);

    for (size_t i = 0; i < input.size(); ++i)
      freq[input[i] - 'A'].second++;

    return freq;
  }

  double correlation(const string& input)
  {
    double result = 0.0;
    frequency(input);

    sort(freq.begin(), freq.end(), [](pair<char, double> u, pair<char, double> v)->bool
      { return u.second < v.second; });

    for (size_t i = 0; i < 26; ++i)
      result += freq[i].second * sortedTargets[i];

    return result;
  }

public:
  VigenereAnalyser(const array<double, 26>& targetFreqs)
  {
    targets = targetFreqs;
    sortedTargets = targets;
    sort(sortedTargets.begin(), sortedTargets.end());
  }

  pair<string, string> analyze(string input)
  {
    string cleaned;
    for (size_t i = 0; i < input.size(); ++i)
    {
      if (input[i] >= 'A' && input[i] <= 'Z')
        cleaned += input[i];
      else if (input[i] >= 'a' && input[i] <= 'z')
        cleaned += input[i] + 'A' - 'a';
    }

    size_t bestLength = 0;
    double bestCorr = -100.0;

    // Assume that if there are less than 20 characters
    // per column, the key's too long to guess
    for (size_t i = 2; i < cleaned.size() / 20; ++i)
    {
      vector<string> pieces(i);
      for (size_t j = 0; j < cleaned.size(); ++j)
        pieces[j % i] += cleaned[j];

      // The correlation increases artificially for smaller
      // pieces/longer keys, so weigh against them a little
      double corr = -0.5*i;
      for (size_t j = 0; j < i; ++j)
        corr += correlation(pieces[j]);

      if (corr > bestCorr)
      {
        bestLength = i;
        bestCorr = corr;
      }
    }

    if (bestLength == 0)
      return make_pair("Text is too short to analyze", "");

    vector<string> pieces(bestLength);
    for (size_t i = 0; i < cleaned.size(); ++i)
      pieces[i % bestLength] += cleaned[i];

    vector<FreqArray> freqs;
    for (size_t i = 0; i < bestLength; ++i)
      freqs.push_back(frequency(pieces[i]));

    string key = "";
    for (size_t i = 0; i < bestLength; ++i)
    {
      sort(freqs[i].begin(), freqs[i].end(), [](pair<char, double> u, pair<char, double> v)->bool
        { return u.second > v.second; });

      size_t m = 0;
      double mCorr = 0.0;
      for (size_t j = 0; j < 26; ++j)
      {
        double corr = 0.0;
        char c = 'A' + j;
        for (size_t k = 0; k < 26; ++k)
        {
          int d = (freqs[i][k].first - c + 26) % 26;
          corr += freqs[i][k].second * targets[d];
        }

        if (corr > mCorr)
        {
          m = j;
          mCorr = corr;
        }
      }

      key += m + 'A';
    }

    string result = "";
    for (size_t i = 0; i < cleaned.size(); ++i)
      result += (cleaned[i] - key[i % key.length()] + 26) % 26 + 'A';

    return make_pair(result, key);
  }
};

int main()
{
  string input =
    "MOMUD EKAPV TQEFM OEVHP AJMII CDCTI FGYAG JSPXY ALUYM NSMYH"
    "VUXJE LEPXJ FXGCM JHKDZ RYICU HYPUS PGIGM OIYHF WHTCQ KMLRD"
    "ITLXZ LJFVQ GHOLW CUHLO MDSOE KTALU VYLNZ RFGBX PHVGA LWQIS"
    "FGRPH JOOFW GUBYI LAPLA LCAFA AMKLG CETDW VOELJ IKGJB XPHVG"
    "ALWQC SNWBU BYHCU HKOCE XJEYK BQKVY KIIEH GRLGH XEOLW AWFOJ"
    "ILOVV RHPKD WIHKN ATUHN VRYAQ DIVHX FHRZV QWMWV LGSHN NLVZS"
    "JLAKI FHXUF XJLXM TBLQV RXXHR FZXGV LRAJI EXPRV OSMNP KEPDT"
    "LPRWM JAZPK LQUZA ALGZX GVLKL GJTUI ITDSU REZXJ ERXZS HMPST"
    "MTEOE PAPJH SMFNB YVQUZ AALGA YDNMP AQOWT UHDBV TSMUE UIMVH"
    "QGVRW AEFSP EMPVE PKXZY WLKJA GWALT VYYOB YIXOK IHPDS EVLEV"
    "RVSGB JOGYW FHKBL GLXYA MVKIS KIEHY IMAPX UOISK PVAGN MZHPW"
    "TTZPV XFCCD TUHJH WLAPF YULTB UXJLN SIJVV YOVDJ SOLXG TGRVO"
    "SFRII CTMKO JFCQF KTINQ BWVHG TENLH HOGCS PSFPV GJOKM SIFPR"
    "ZPAAS ATPTZ FTPPD PORRF TAXZP KALQA WMIUD BWNCT LEFKO ZQDLX"
    "BUXJL ASIMR PNMBF ZCYLV WAPVF QRHZV ZGZEF KBYIO OFXYE VOWGB"
    "BXVCB XBAWG LQKCM ICRRX MACUO IKHQU AJEGL OIJHH XPVZW JEWBA"
    "FWAML ZZRXJ EKAHV FASMU LVVUT TGK";

  array<double, 26> english = {
    0.08167, 0.01492, 0.02782, 0.04253, 0.12702, 0.02228,
    0.02015, 0.06094, 0.06966, 0.00153, 0.00772, 0.04025,
    0.02406, 0.06749, 0.07507, 0.01929, 0.00095, 0.05987,
    0.06327, 0.09056, 0.02758, 0.00978, 0.02360, 0.00150,
    0.01974, 0.00074};

  VigenereAnalyser va(english);
  pair<string, string> output = va.analyze(input);

  cout << "Key: " << output.second << endl << endl;
  cout << "Text: " << output.first << endl;
}


import std.stdio, std.algorithm, std.typecons, std.string,
       std.array, std.numeric, std.ascii;

string[2] vigenereDecrypt(in double[] targetFreqs, in string input) {
    enum nAlpha = std.ascii.uppercase.length;

    static double correlation(in string txt, in double[] sTargets)
    pure nothrow /*@safe*/ @nogc {
        uint[nAlpha] charCounts = 0;
        foreach (immutable c; txt)
            charCounts[c - 'A']++;
        return charCounts[].sort().release.dotProduct(sTargets);
    }

    static frequency(in string txt) pure nothrow @safe {
        auto freqs = new Tuple!(char,"c", uint,"d")[nAlpha];
        foreach (immutable i, immutable c; std.ascii.uppercase)
            freqs[i] = tuple(c, 0);
        foreach (immutable c; txt)
            freqs[c - 'A'].d++;
        return freqs;
    }

    static string[2] decode(in string cleaned, in string key)
    pure nothrow @safe {
        assert(!key.empty);
        string decoded;
        foreach (immutable i, immutable c; cleaned)
            decoded ~= (c - key[i % $] + nAlpha) % nAlpha + 'A';
        return [key, decoded];
    }

    static size_t findBestLength(in string cleaned,
                                 in double[] sTargets)
    pure nothrow /*@safe*/ {
        size_t bestLength;
        double bestCorr = -100.0;

        // Assume that if there are less than 20 characters
        // per column, the key's too long to guess
        foreach (immutable i; 2 .. cleaned.length / 20) {
            auto pieces = new Appender!string[i];
            foreach (immutable j, immutable c; cleaned)
                pieces[j % i] ~= c;

            // The correlation seems to increase for smaller
            // pieces/longer keys, so weigh against them a little
            double corr = -0.5 * i;
            foreach (const p; pieces)
                corr += correlation(p.data, sTargets);

            if (corr > bestCorr) {
                bestLength = i;
                bestCorr = corr;
            }
        }

        return bestLength;
    }

    static string findKey(in string cleaned, in size_t bestLength,
                          in double[] targetFreqs) pure nothrow @safe {
        auto pieces = new string[bestLength];
        foreach (immutable i, immutable c; cleaned)
            pieces[i % bestLength] ~= c;

        string key;
        foreach (fr; pieces.map!frequency) {
            fr.sort!q{ a.d > b.d };

            size_t m;
            double maxCorr = 0.0;
            foreach (immutable j, immutable c; uppercase) {
                double corr = 0.0;
                foreach (immutable frc; fr) {
                    immutable di = (frc.c - c + nAlpha) % nAlpha;
                    corr += frc.d * targetFreqs[di];
                }

                if (corr > maxCorr) {
                    m = j;
                    maxCorr = corr;
                }
            }

            key ~= m + 'A';
        }

        return key;
    }

    immutable cleaned = input.toUpper.removechars("^A-Z");

    //immutable sortedTargets = targetFreqs.sorted;
    immutable sortedTargets = targetFreqs.dup.sort().release.idup;

    immutable bestLength = findBestLength(cleaned, sortedTargets);
    if (bestLength == 0)
        throw new Exception("Text is too short to analyze.");

    immutable string key = findKey(cleaned, bestLength, targetFreqs);
    return decode(cleaned, key);
}

void main() {
    immutable encoded = "MOMUD EKAPV TQEFM OEVHP AJMII CDCTI FGYAG
JSPXY ALUYM NSMYH VUXJE LEPXJ FXGCM JHKDZ RYICU HYPUS PGIGM OIYHF
WHTCQ KMLRD ITLXZ LJFVQ GHOLW CUHLO MDSOE KTALU VYLNZ RFGBX PHVGA
LWQIS FGRPH JOOFW GUBYI LAPLA LCAFA AMKLG CETDW VOELJ IKGJB XPHVG
ALWQC SNWBU BYHCU HKOCE XJEYK BQKVY KIIEH GRLGH XEOLW AWFOJ ILOVV
RHPKD WIHKN ATUHN VRYAQ DIVHX FHRZV QWMWV LGSHN NLVZS JLAKI FHXUF
XJLXM TBLQV RXXHR FZXGV LRAJI EXPRV OSMNP KEPDT LPRWM JAZPK LQUZA
ALGZX GVLKL GJTUI ITDSU REZXJ ERXZS HMPST MTEOE PAPJH SMFNB YVQUZ
AALGA YDNMP AQOWT UHDBV TSMUE UIMVH QGVRW AEFSP EMPVE PKXZY WLKJA
GWALT VYYOB YIXOK IHPDS EVLEV RVSGB JOGYW FHKBL GLXYA MVKIS KIEHY
IMAPX UOISK PVAGN MZHPW TTZPV XFCCD TUHJH WLAPF YULTB UXJLN SIJVV
YOVDJ SOLXG TGRVO SFRII CTMKO JFCQF KTINQ BWVHG TENLH HOGCS PSFPV
GJOKM SIFPR ZPAAS ATPTZ FTPPD PORRF TAXZP KALQA WMIUD BWNCT LEFKO
ZQDLX BUXJL ASIMR PNMBF ZCYLV WAPVF QRHZV ZGZEF KBYIO OFXYE VOWGB
BXVCB XBAWG LQKCM ICRRX MACUO IKHQU AJEGL OIJHH XPVZW JEWBA FWAML
ZZRXJ EKAHV FASMU LVVUT TGK";

    immutable englishFrequences = [0.08167, 0.01492, 0.02782, 0.04253,
        0.12702, 0.02228, 0.02015, 0.06094, 0.06966, 0.00153, 0.00772,
        0.04025, 0.02406, 0.06749, 0.07507, 0.01929, 0.00095, 0.05987,
        0.06327, 0.09056, 0.02758, 0.00978, 0.02360, 0.00150, 0.01974,
        0.00074];

    immutable key_dec = vigenereDecrypt(englishFrequences, encoded);
    writefln("Key: %s\n\nText: %s", key_dec[0], key_dec[1]);
}