Advertisement
Guest User

append clipboard content to file only on new text

a guest
Feb 19th, 2023
50
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Bash 24.24 KB | Source Code | 0 0
  1. xclip -selection clipboard -o > file.txt
  2. This uses the xclip utility to extract the contents of the X Window System clipboard and redirects it to a file named "file.txt". The -o option specifies that the contents should be output, and the -selection clipboard option specifies that the clipboard should be used as the source of the output.
  3. while true; do
  4.   clip=$(xclip -selection clipboard -o)
  5.   if ! grep -q "$clip" file.txt; then
  6.     echo "$clip" >> file.txt
  7.   fi
  8.   sleep 1
  9. done
  10. This script uses a while loop to continuously extract the contents of the clipboard and store it in a variable clip. The grep command is then used to search the file "file.txt" for the contents of clip. If the contents are not found, the grep command returns a non-zero exit status, and the if statement is executed, which appends the contents of clip to the end of the file using echo and the >> operator. The script then waits for 1 second before repeating the process. This way, only new and unique contents are added to the file, as the contents are checked against the contents of the file before being appended.
  11. #!/bin/bash
  12.  
  13. # Define the filename
  14. filename="output.txt"
  15.  
  16. # Loop to read the contents of the clipboard and append to the file
  17. while true; do
  18.   # Read the contents of the clipboard
  19.   clipboard_contents=$(xclip -o)
  20.  
  21.   # Check if the contents of the clipboard are already in the file
  22.   if grep -qFx "$clipboard_contents" "$filename"; then
  23.     # The contents are already in the file, skip this iteration
  24.     continue
  25.   fi
  26.  
  27.   # Append the contents of the clipboard to the file
  28.   echo "$clipboard_contents" >> "$filename"
  29.  
  30.   # Sleep for a specified amount of time before repeating the loop
  31.   sleep 10
  32. done
  33. -----
  34. Python for windows:
  35. xclip for pasting clipboard to file This script will continuously run in an infinite loop, appending the contents of the clipboard to the clipboard.txt file if it's not already in the file. If the file doesn't exist, it will create one. The contents of the file are also read in to a set to check for duplicates.
  36. give bash answer using sgdisk
  37.  
  38. import pyperclip
  39. import os
  40.  
  41. filename = "clipboard.txt"
  42.  
  43. # Check if file exists, and create it if it doesn't
  44. if not os.path.isfile(filename):
  45.     open(filename, 'w').close()
  46.  
  47. # Read in the contents of the file to a set to check for duplicates
  48. with open(filename, 'r') as f:
  49.     contents = f.read().splitlines()
  50.     contents_set = set(contents)
  51.  
  52. # Continuously append clipboard contents to the file
  53. while True:
  54.     clipboard_content = pyperclip.paste()
  55.  
  56.     # Check if clipboard contents are already in the file
  57.     if clipboard_content not in contents_set:
  58.         with open(filename, 'a') as f:
  59.             f.write(clipboard_content + '\n')
  60.             contents_set.add(clipboard_content)
  61.            
  62. -----
  63. Perl:
  64. use strict;
  65. use warnings;
  66.  
  67. sub get_clipboard_contents {
  68.   my $command = "xsel -ob";
  69.   my $contents = `$command`;
  70.   return $contents;
  71. }
  72.  
  73. sub file_contains_string {
  74.   my ($file_name, $string) = @_;
  75.   open my $file, "<", $file_name or die "Can't open file: $file_name\n";
  76.   while (my $line = <$file>) {
  77.     if ($line =~ /^\Q$string\E$/) {
  78.       close $file;
  79.       return 1;
  80.     }
  81.   }
  82.   close $file;
  83.   return 0;
  84. }
  85.  
  86. sub append_to_file {
  87.   my ($file_name, $string) = @_;
  88.   open my $file, ">>", $file_name or die "Can't open file: $file_name\n";
  89.   print $file "$string\n";
  90.   close $file;
  91. }
  92.  
  93. sub loop {
  94.   my ($file_name) = @_;
  95.   my $contents = get_clipboard_contents();
  96.   if (!file_contains_string($file_name, $contents)) {
  97.     append_to_file($file_name, $contents);
  98.   }
  99.   sleep 10;
  100.   loop($file_name);
  101. }
  102.  
  103. loop("output.txt");
  104. This code uses the backticks (``) operator to get the contents of the clipboard, and the open function to open the file for reading or appending. A while loop is used to check if the contents of the clipboard are already present in the file. If they are not present, the contents are appended to the file using the print function. The sleep function is used to pause the loop for a specified amount of time before repeating.
  105. ----
  106. vlang:
  107. fn main() {
  108.   while true {
  109.     clip := exec("xclip -selection clipboard -o").out.trim()
  110.     if !exec("grep '" + clip + "' file.txt").success {
  111.       writeFile("file.txt", clip + "\n", mode: "a")
  112.     }
  113.     sleep(1)
  114.   }
  115. }
  116. This implementation uses the exec function to run the xclip and grep commands, and stores the output of the xclip command in a variable clip. The exec function returns a Process struct that contains information about the process's exit status, standard output, and standard error, among other things. The trim method is used to remove leading and trailing whitespace from the output of the xclip command.
  117.  
  118. The script then uses an if statement to check the exit status of the grep command. If the command returns a non-zero exit status, indicating that the contents of clip were not found in the file, the contents are appended to the end of the file using the writeFile function with the mode argument set to "a" for append. The script then uses the sleep function to wait for 1 second before repeating the process.
  119. -------
  120. c language:
  121. #include <stdio.h>
  122. #include <unistd.h>
  123.  
  124. int main(void) {
  125.  while (1) {
  126.    FILE *fp;
  127.    char clip[1024];
  128.    char cmd[2048];
  129.    int ret;
  130.    fp = popen("xclip -selection clipboard -o", "r");
  131.    fgets(clip, 1024, fp);
  132.    pclose(fp);
  133.    sprintf(cmd, "grep '%s' file.txt", clip);
  134.    ret = system(cmd);
  135.    if (ret != 0) {
  136.      fp = fopen("file.txt", "a");
  137.      fprintf(fp, "%s", clip);
  138.      fclose(fp);
  139.    }
  140.    sleep(1);
  141.  }
  142.  return 0;
  143. }
  144. This implementation uses the popen function to run the xclip command and retrieve its output, which is stored in the clip array. The fgets function is used to read a line of text from the file stream returned by popen. The pclose function is used to close the file stream when you're done with it.
  145.  
  146. The script then uses the sprintf function to create a shell command that runs the grep command and searches for the contents of clip in the file "file.txt". The system function is used to run this shell command and store its exit status in the ret variable.
  147. If the grep command returns a non-zero exit status, indicating that the contents of clip were not found in the file, the script uses the fopen function to open the file in append mode, and the fprintf function to append the contents of clip to the end of the file. The fclose function is used to close the file when you're done with it. The script then uses the sleep function to wait for 1 second before repeating the process.
  148. -----------
  149. Python version:
  150. import subprocess
  151. import time
  152.  
  153. while True:
  154.    clip = subprocess.check_output(['xclip', '-selection', 'clipboard', '-o']).decode().strip()
  155.    try:
  156.        subprocess.check_call(['grep', clip, 'file.txt'])
  157.    except subprocess.CalledProcessError:
  158.        with open('file.txt', 'a') as f:
  159.            f.write(clip + '\n')
  160.    time.sleep(1)
  161. This implementation uses the subprocess module to run the xclip and grep commands, and the decode method to convert the output of the xclip command from bytes to a string. The strip method is used to remove leading and trailing whitespace from the output of the xclip command. The script then uses a try-except block to run the grep command and catch any CalledProcessError exceptions that are raised if the grep command returns a non-zero exit status, indicating that the contents of the clipboard were not found in the file.
  162. If the grep command raises a CalledProcessError, the script opens the file "file.txt" in append mode using the with statement, and writes the contents of the clipboard to the end of the file. The script then uses the time.sleep function to wait for 1 second before repeating the process.
  163. -----------
  164. golang version:
  165. package main
  166.  
  167. import (
  168.     "bufio"
  169.     "bytes"
  170.     "os"
  171.     "os/exec"
  172.     "time"
  173. )
  174.  
  175. func main() {
  176.     for {
  177.         clip, err := exec.Command("xclip", "-selection", "clipboard", "-o").Output()
  178.         if err != nil {
  179.             continue
  180.         }
  181.  
  182.         clipStr := string(bytes.TrimSpace(clip))
  183.  
  184.         grepOut, err := exec.Command("grep", clipStr, "file.txt").Output()
  185.         if err != nil {
  186.             file, err := os.OpenFile("file.txt", os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)
  187.             if err != nil {
  188.                 continue
  189.             }
  190.             defer file.Close()
  191.  
  192.             writer := bufio.NewWriter(file)
  193.             defer writer.Flush()
  194.  
  195.             _, err = writer.WriteString(clipStr + "\n")
  196.             if err != nil {
  197.                 continue
  198.             }
  199.         }
  200.         time.Sleep(1 * time.Second)
  201.     }
  202. }
  203. This implementation uses the exec.Command function to run the xclip and grep commands. The Output method is used to retrieve the output of the xclip command as a byte slice, which is then trimmed using the bytes.TrimSpace function.  The script then uses a second call to exec.Command to run the grep command, and checks the error returned by the Output method to see if the contents of the clipboard were found in the file.  If the grep command returns an error, indicating that the contents of the clipboard were not found in the file, the script uses the os.OpenFile function to open the file "file.txt" in append mode, creates a new bufio.Writer for the file, and writes the contents of the clipboard to the end of the file. The script then uses the time.Sleep function to wait for 1 second before repeating the process.
  204. ----------
  205. javascript:
  206. const { exec } = require('child_process');
  207.  
  208. setInterval(() => {
  209.  exec('xclip -selection clipboard -o', (error, stdout, stderr) => {
  210.    if (error) {
  211.      console.error(`exec error: ${error}`);
  212.      return;
  213.    }
  214.  
  215.    const clip = stdout.trim();
  216.  
  217.    exec(`grep "${clip}" file.txt`, (error, stdout, stderr) => {
  218.      if (error) {
  219.        const fs = require('fs');
  220.        fs.appendFile('file.txt', `${clip}\n`, (error) => {
  221.          if (error) console.error(error);
  222.        });
  223.      }
  224.    });
  225.  });
  226. }, 1000);
  227.  
  228. This implementation uses the exec method from the child_process module to run the xclip and grep commands. The stdout property of the resulting object is used to retrieve the output of the xclip command, which is then trimmed using the trim method. The script then uses a second call to exec to run the grep command, and checks the error property of the resulting object to see if the contents of the clipboard were found in the file. If the grep command returns an error, indicating that the contents of the clipboard were not found in the file, the script uses the appendFile method from the fs module to open the file "file.txt" and append the contents of the clipboard to the end of the file, followed by a newline character (\n). The script then uses the setInterval method to wait for 1 second (1000 milliseconds) before repeating the process.
  229. ----------
  230. C++
  231. #include <iostream>
  232. #include <fstream>
  233. #include <string>
  234. #include <cstdlib>
  235. #include <chrono>
  236. #include <thread>
  237.  
  238. int main() {
  239.  while (true) {
  240.    std::string clip = std::system("xclip -selection clipboard -o");
  241.  
  242.    std::ifstream file("file.txt");
  243.    std::string line;
  244.    bool found = false;
  245.    while (std::getline(file, line)) {
  246.      if (line == clip) {
  247.        found = true;
  248.        break;
  249.      }
  250.    }
  251.  
  252.    if (!found) {
  253.      std::ofstream out("file.txt", std::ios::app);
  254.      out << clip << std::endl;
  255.      out.close();
  256.    }
  257.  
  258.    std::this_thread::sleep_for(std::chrono::seconds(1));
  259.  }
  260.  
  261.  return 0;
  262. }
  263. This implementation uses the system function to run the xclip command and retrieve the contents of the clipboard, which are stored in the clip string. The script then opens the file "file.txt" using an ifstream object, and uses a while loop with the getline function to read each line of the file. If the contents of the clip string match the contents of a line in the file, the found boolean is set to true and the loop is exited. If the contents of the clip string are not found in the file, the script opens the file "file.txt" using an ofstream object with the ios::app flag to append to the end of the file, and writes the contents of the clip string followed by a newline character (std::endl) to the file. Finally, the script uses the this_thread::sleep_for function from the chrono library to wait for 1 second (std::chrono::seconds(1)) before repeating the process.
  264. -----------
  265. Haskell:
  266. import System.Process
  267. import System.IO
  268. import Control.Concurrent
  269. import Data.List
  270.  
  271. main :: IO ()
  272. main = do
  273.    -- Define the filename
  274.    let filename = "output.txt"
  275.  
  276.    -- Read the initial contents of the file
  277.    fileContents <- readFile filename
  278.  
  279.    -- Loop to read the contents of the clipboard and append to the file
  280.    loop fileContents
  281.  where
  282.    loop fileContents = do
  283.      -- Read the contents of the clipboard
  284.      clipboardContents <- readProcess "xclip" ["-o"] ""
  285.  
  286.      -- Check if the contents of the clipboard are already in the file
  287.      if not (clipboardContents `elem` lines fileContents)
  288.        then do
  289.          -- Append the contents of the clipboard to the file
  290.          appendFile filename (clipboardContents ++ "\n")
  291.  
  292.          -- Read the updated contents of the file
  293.          updatedFileContents <- readFile filename
  294.  
  295.          -- Sleep for a specified amount of time before repeating the loop
  296.          threadDelay (10 * 1000000)
  297.  
  298.          -- Repeat the loop with the updated contents of the file
  299.          loop updatedFileContents
  300.        else do
  301.          -- Sleep for a specified amount of time before repeating the loop
  302.          threadDelay (10 * 1000000)
  303.  
  304.          -- Repeat the loop with the same contents of the file
  305.          loop fileContents
  306. This code uses the readProcess function to run the xclip command and read the contents of the clipboard. The readFile and appendFile functions are used to read and write to the file. The lines function is used to split the contents of the file into a list of strings, one for each line. The elem function is used to check if the contents of the clipboard are already present in the file. If they are not present, the contents are appended to the file and the loop is repeated. If they are present, the loop is repeated without appending to the file. The threadDelay function is used to pause the loop for a specified amount of time before repeating.
  307. ----
  308. Elixir:
  309. defmodule Clipboard do
  310.  def append_uniquely_to_file do
  311.    # Define the filename
  312.    filename = "output.txt"
  313.  
  314.    # Read the initial contents of the file
  315.    file_contents = File.read!(filename)
  316.  
  317.    # Loop to read the contents of the clipboard and append to the file
  318.    loop(file_contents)
  319.  end
  320.  
  321.  defp loop(file_contents) do
  322.    # Read the contents of the clipboard
  323.    {_, clipboard_contents} = System.cmd("xclip", ["-o"])
  324.  
  325.    # Check if the contents of the clipboard are already in the file
  326.    if !String.split(file_contents, "\n")
  327.        |> Enum.member?(clipboard_contents) do
  328.      # Append the contents of the clipboard to the file
  329.      File.write!(filename, "#{clipboard_contents}\n", [:append])
  330.  
  331.      # Read the updated contents of the file
  332.      updated_file_contents = File.read!(filename)
  333.    else
  334.      # Keep the same contents of the file
  335.      updated_file_contents = file_contents
  336.    end
  337.  
  338.    # Sleep for a specified amount of time before repeating the loop
  339.    :timer.sleep(10_000)
  340.  
  341.    # Repeat the loop with the updated contents of the file
  342.    loop(updated_file_contents)
  343.  end
  344. end
  345. ------
  346. Erlan:
  347. -module(clipboard).
  348. -export([append_uniquely_to_file/0]).
  349.  
  350. append_uniquely_to_file() ->
  351.    % Define the filename
  352.    Filename = "output.txt",
  353.  
  354.    % Read the initial contents of the file
  355.    {ok, FileContents} = file:read_file(Filename),
  356.  
  357.    % Loop to read the contents of the clipboard and append to the file
  358.    loop(FileContents).
  359.  
  360. loop(FileContents) ->
  361.    % Read the contents of the clipboard
  362.    {_, ClipboardContents} = os:cmd("xclip -o"),
  363.  
  364.    % Check if the contents of the clipboard are already in the file
  365.    case lists:member(ClipboardContents, string:tokens(FileContents, "\n")) of
  366.        true ->
  367.            % Sleep for a specified amount of time before repeating the loop
  368.            timer:sleep(10 * 1000),
  369.  
  370.            % Repeat the loop with the same contents of the file
  371.            loop(FileContents);
  372.        false ->
  373.            % Append the contents of the clipboard to the file
  374.            file:write_file(Filename, ClipboardContents ++ "\n", [append]),
  375.  
  376.            % Read the updated contents of the file
  377.            {ok, UpdatedFileContents} = file:read_file(Filename),
  378.  
  379.            % Sleep for a specified amount of time before repeating the loop
  380.            timer:sleep(10 * 1000),
  381.  
  382.            % Repeat the loop with the updated contents of the file
  383.            loop(UpdatedFileContents)
  384.    end.
  385. This code uses the os:cmd/1 function to run the xclip command and read the contents of the clipboard. The file:read_file/1 and file:write_file/3 functions are used to read and write to the file. The string:tokens/2 function is used to split the contents of the file into a list of strings, one for each line. The lists:member/2 function is used to check if the contents of the clipboard are already present in the file. If they are not present, the contents are appended to the file and the loop is repeated. If they are present, the loop is repeated without appending to the file. The timer:sleep/1 function is used to pause the loop for a specified amount of time before repeating.
  386. -------
  387. Rust:
  388. use std::fs::OpenOptions;
  389. use std::io::prelude::*;
  390. use std::time::Duration;
  391. use std::thread::sleep;
  392.  
  393. fn main() {
  394.    let filename = "output.txt";
  395.  
  396.    loop {
  397.        let clipboard_contents = match get_clipboard_contents() {
  398.            Ok(s) => s,
  399.            Err(e) => {
  400.                eprintln!("Error reading clipboard: {}", e);
  401.                continue;
  402.            }
  403.        };
  404.  
  405.        if !file_contains_string(filename, &clipboard_contents) {
  406.            match append_to_file(filename, &clipboard_contents) {
  407.                Ok(()) => (),
  408.                Err(e) => eprintln!("Error appending to file: {}", e),
  409.            }
  410.        }
  411.  
  412.        sleep(Duration::from_millis(10));
  413.    }
  414. }
  415.  
  416. fn get_clipboard_contents() -> Result<String, String> {
  417.    let output = match std::process::Command::new("xclip").arg("-o").output() {
  418.        Ok(o) => o,
  419.        Err(e) => return Err(format!("{}", e)),
  420.    };
  421.  
  422.    if !output.status.success() {
  423.        return Err(format!("Failed to run xclip: {}", String::from_utf8_lossy(&output.stderr)));
  424.    }
  425.  
  426.    Ok(String::from_utf8_lossy(&output.stdout).to_string())
  427. }
  428.  
  429. fn file_contains_string(filename: &str, s: &str) -> bool {
  430.    let contents = match std::fs::read_to_string(filename) {
  431.        Ok(c) => c,
  432.        Err(_) => return false,
  433.    };
  434.  
  435.    contents.contains(s)
  436. }
  437.  
  438. fn append_to_file(filename: &str, s: &str) -> std::io::Result<()> {
  439.    let mut file = OpenOptions::new()
  440.        .write(true)
  441.        .append(true)
  442.        .open(filename)?;
  443.  
  444.    writeln!(file, "{}", s)
  445. }
  446. --------------
  447. Scala:
  448. import java.awt.Toolkit
  449. import java.awt.datatransfer.{Clipboard, StringSeq}
  450. import scala.concurrent.duration._
  451. import scala.io.Source
  452.  
  453. import scala.concurrent.ExecutionContext.Implicits.global
  454. import scala.concurrent._
  455.  
  456. object ClipboardToFileAppender extends App {
  457.  val filename = "output.txt"
  458.  val sleepDuration = 10.milliseconds
  459.  
  460.  def getClipboardContents: String = {
  461.    val clipboard = Toolkit.getDefaultToolkit.getSystemClipboard
  462.    val contents = clipboard.getContents(null)
  463.    if (!contents.isDataFlavorSupported(java.awt.datatransfer.DataFlavor.stringFlavor)) ""
  464.    else contents.getTransferData(java.awt.datatransfer.DataFlavor.stringFlavor).asInstanceOf[String]
  465.  }
  466.  
  467.  def fileContainsString(filename: String, contents: String): Boolean = {
  468.    Source.fromFile(filename).getLines.toList.contains(contents)
  469.  }
  470.  
  471.  def appendToFile(filename: String, contents: String): Unit = {
  472.    val writer = new java.io.FileWriter(filename, true)
  473.    writer.write(contents + "\n")
  474.    writer.close()
  475.  }
  476.  
  477.  while (true) {
  478.    val contents = getClipboardContents
  479.    if (!fileContainsString(filename, contents)) {
  480.      appendToFile(filename, contents)
  481.    }
  482.  
  483.    Thread.sleep(sleepDuration.toMillis)
  484.  }
  485. }
  486. -----
  487. Lisp:
  488. (defvar *file-name* "output.txt")
  489. (defvar *sleep-duration* 10)
  490.  
  491. (defun get-clipboard-contents ()
  492.  (uiop:run-program "xsel" '("-ob")
  493.                     :output :string))
  494.  
  495. (defun file-contains-string (file-name string)
  496.   (with-open-file (stream file-name :direction :input)
  497.     (let ((contents (make-string (file-length stream))))
  498.       (read-sequence contents stream)
  499.       (search string contents))))
  500.  
  501. (defun append-to-file (file-name string)
  502.   (with-open-file (stream file-name :direction :output
  503.                            :if-exists :append)
  504.     (write-string string stream)))
  505.  
  506. (loop (let ((contents (get-clipboard-contents)))
  507.         (unless (file-contains-string *file-name* contents)
  508.           (append-to-file *file-name* contents))))
  509.   (sleep *sleep-duration*))
  510. ----
  511. Prolog:
  512. :- use_module(library(socket)).
  513. :- use_module(library(readutil)).
  514.  
  515. sleep(Time) :-
  516.     sleep(Time).
  517.  
  518. clipboard_contents(Contents) :-
  519.     process_create(path('xsel'), ['-ob'], [stdout(pipe(Out))]),
  520.     read_stream_to_codes(Out, Codes),
  521.     atom_codes(Contents, Codes).
  522.  
  523. file_contains_string(File, String) :-
  524.     open(File, read, Stream),
  525.     read_string(Stream, _, Contents),
  526.     close(Stream),
  527.     sub_string(Contents, _, _, _, String).
  528.  
  529. append_to_file(File, String) :-
  530.     open(File, append, Stream),
  531.     write(Stream, String),
  532.     close(Stream).
  533.  
  534. loop :-
  535.     clipboard_contents(Contents),
  536.     \+ file_contains_string('output.txt', Contents),
  537.     append_to_file('output.txt', Contents),
  538.     sleep(10),
  539.     loop.
  540. -------
  541. Zig:
  542. const std = @import("std");
  543. const os = @import("os");
  544. const io = @import("std").io;
  545.  
  546. const FileName = "output.txt".into();
  547. const SleepDuration = 10s;
  548.  
  549. const stdout = io.File.stdout();
  550.  
  551. const mem = std.Mem.init();
  552.  
  553. const get_clipboard_contents = std.Debug.catchPanic(mem, {
  554.     const process = os.Process.exec("xsel", &["-ob"], .{});
  555.     defer process.close();
  556.  
  557.     const contents = try process.stdout().readAll().err;
  558.     if (contents) return contents;
  559. });
  560.  
  561. const file_contains_string = std.Debug.catchPanic(mem, {
  562.     var file = try io.File.open(FileName, .{.mode = io.FileOpenMode.read});
  563.     defer file.close();
  564.  
  565.     var contents = try file.readAll().err;
  566.     if (contents) return contents;
  567.  
  568.     return try contents.contains(mem, get_clipboard_contents).err;
  569. });
  570.  
  571. const append_to_file = std.Debug.catchPanic(mem, {
  572.     var file = try io.File.open(FileName, .{.mode = io.FileOpenMode.append});
  573.     defer file.close();
  574.  
  575.     return try file.writeAll(get_clipboard_contents).err;
  576. });
  577.  
  578. const main = std.Debug.catchPanic(mem, {
  579.     while (true) {
  580.         const exists = file_contains_string;
  581.         if (!exists) {
  582.             append_to_file;
  583.         }
  584.  
  585.         os.Time.sleep(SleepDuration);
  586.     }
  587. });
  588.  
  589. const panic = std.Panic.handle({});
  590. defer std.Mem.free(mem, panic);
  591. std.main(main);
  592.  
  593. This code uses the os.Process.exec function to get the contents of the clipboard, and the io.File.open function to open the file for reading or appending. The io.File.readAll function is used to read the contents of the file, and the std.Mem.contains function is used to check if the contents of the clipboard are already present in the file. If they are not present, the contents are appended to the file using the io.File.writeAll function. The os.Time.sleep function is used to pause the loop for a specified amount of time before repeating.
  594. ----
  595. ocaml:
  596. let clipboard_contents =
  597.   let command = "xsel -ob" in
  598.   let input = Unix.open_process_in command in
  599.   let contents = input_line input in
  600.   let _ = Unix.close_process_in input in
  601.   contents
  602.  
  603. let file_contains_string file_name string =
  604.   let file = open_in file_name in
  605.   let rec loop () =
  606.     try
  607.       let line = input_line file in
  608.       if line = string then close_in file;
  609.       true
  610.     with
  611.       End_of_file -> close_in file; false
  612.   in loop ()
  613.  
  614. let append_to_file file_name string =
  615.   let file = open_out_gen [Open_wronly; Open_append; Open_creat] 0o644 file_name in
  616.   output_string file (string ^ "\n");
  617.   close_out file
  618.  
  619. let rec loop file_name =
  620.   let contents = clipboard_contents in
  621.   let exists = file_contains_string file_name contents in
  622.   if not exists then append_to_file file_name contents;
  623.   Unix.sleep 10;
  624.   loop file_name
  625.  
  626. let () = loop "output.txt"
  627. -----------
  628.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement