Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- xclip -selection clipboard -o > file.txt
- 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.
- while true; do
- clip=$(xclip -selection clipboard -o)
- if ! grep -q "$clip" file.txt; then
- echo "$clip" >> file.txt
- fi
- sleep 1
- done
- 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.
- #!/bin/bash
- # Define the filename
- filename="output.txt"
- # Loop to read the contents of the clipboard and append to the file
- while true; do
- # Read the contents of the clipboard
- clipboard_contents=$(xclip -o)
- # Check if the contents of the clipboard are already in the file
- if grep -qFx "$clipboard_contents" "$filename"; then
- # The contents are already in the file, skip this iteration
- continue
- fi
- # Append the contents of the clipboard to the file
- echo "$clipboard_contents" >> "$filename"
- # Sleep for a specified amount of time before repeating the loop
- sleep 10
- done
- -----
- Python for windows:
- 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.
- give bash answer using sgdisk
- import pyperclip
- import os
- filename = "clipboard.txt"
- # Check if file exists, and create it if it doesn't
- if not os.path.isfile(filename):
- open(filename, 'w').close()
- # Read in the contents of the file to a set to check for duplicates
- with open(filename, 'r') as f:
- contents = f.read().splitlines()
- contents_set = set(contents)
- # Continuously append clipboard contents to the file
- while True:
- clipboard_content = pyperclip.paste()
- # Check if clipboard contents are already in the file
- if clipboard_content not in contents_set:
- with open(filename, 'a') as f:
- f.write(clipboard_content + '\n')
- contents_set.add(clipboard_content)
- -----
- Perl:
- use strict;
- use warnings;
- sub get_clipboard_contents {
- my $command = "xsel -ob";
- my $contents = `$command`;
- return $contents;
- }
- sub file_contains_string {
- my ($file_name, $string) = @_;
- open my $file, "<", $file_name or die "Can't open file: $file_name\n";
- while (my $line = <$file>) {
- if ($line =~ /^\Q$string\E$/) {
- close $file;
- return 1;
- }
- }
- close $file;
- return 0;
- }
- sub append_to_file {
- my ($file_name, $string) = @_;
- open my $file, ">>", $file_name or die "Can't open file: $file_name\n";
- print $file "$string\n";
- close $file;
- }
- sub loop {
- my ($file_name) = @_;
- my $contents = get_clipboard_contents();
- if (!file_contains_string($file_name, $contents)) {
- append_to_file($file_name, $contents);
- }
- sleep 10;
- loop($file_name);
- }
- loop("output.txt");
- 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.
- ----
- vlang:
- fn main() {
- while true {
- clip := exec("xclip -selection clipboard -o").out.trim()
- if !exec("grep '" + clip + "' file.txt").success {
- writeFile("file.txt", clip + "\n", mode: "a")
- }
- sleep(1)
- }
- }
- 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.
- 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.
- -------
- c language:
- #include <stdio.h>
- #include <unistd.h>
- int main(void) {
- while (1) {
- FILE *fp;
- char clip[1024];
- char cmd[2048];
- int ret;
- fp = popen("xclip -selection clipboard -o", "r");
- fgets(clip, 1024, fp);
- pclose(fp);
- sprintf(cmd, "grep '%s' file.txt", clip);
- ret = system(cmd);
- if (ret != 0) {
- fp = fopen("file.txt", "a");
- fprintf(fp, "%s", clip);
- fclose(fp);
- }
- sleep(1);
- }
- return 0;
- }
- 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.
- 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.
- 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.
- -----------
- Python version:
- import subprocess
- import time
- while True:
- clip = subprocess.check_output(['xclip', '-selection', 'clipboard', '-o']).decode().strip()
- try:
- subprocess.check_call(['grep', clip, 'file.txt'])
- except subprocess.CalledProcessError:
- with open('file.txt', 'a') as f:
- f.write(clip + '\n')
- time.sleep(1)
- 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.
- 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.
- -----------
- golang version:
- package main
- import (
- "bufio"
- "bytes"
- "os"
- "os/exec"
- "time"
- )
- func main() {
- for {
- clip, err := exec.Command("xclip", "-selection", "clipboard", "-o").Output()
- if err != nil {
- continue
- }
- clipStr := string(bytes.TrimSpace(clip))
- grepOut, err := exec.Command("grep", clipStr, "file.txt").Output()
- if err != nil {
- file, err := os.OpenFile("file.txt", os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644)
- if err != nil {
- continue
- }
- defer file.Close()
- writer := bufio.NewWriter(file)
- defer writer.Flush()
- _, err = writer.WriteString(clipStr + "\n")
- if err != nil {
- continue
- }
- }
- time.Sleep(1 * time.Second)
- }
- }
- 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.
- ----------
- javascript:
- const { exec } = require('child_process');
- setInterval(() => {
- exec('xclip -selection clipboard -o', (error, stdout, stderr) => {
- if (error) {
- console.error(`exec error: ${error}`);
- return;
- }
- const clip = stdout.trim();
- exec(`grep "${clip}" file.txt`, (error, stdout, stderr) => {
- if (error) {
- const fs = require('fs');
- fs.appendFile('file.txt', `${clip}\n`, (error) => {
- if (error) console.error(error);
- });
- }
- });
- });
- }, 1000);
- 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.
- ----------
- C++
- #include <iostream>
- #include <fstream>
- #include <string>
- #include <cstdlib>
- #include <chrono>
- #include <thread>
- int main() {
- while (true) {
- std::string clip = std::system("xclip -selection clipboard -o");
- std::ifstream file("file.txt");
- std::string line;
- bool found = false;
- while (std::getline(file, line)) {
- if (line == clip) {
- found = true;
- break;
- }
- }
- if (!found) {
- std::ofstream out("file.txt", std::ios::app);
- out << clip << std::endl;
- out.close();
- }
- std::this_thread::sleep_for(std::chrono::seconds(1));
- }
- return 0;
- }
- 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.
- -----------
- Haskell:
- import System.Process
- import System.IO
- import Control.Concurrent
- import Data.List
- main :: IO ()
- main = do
- -- Define the filename
- let filename = "output.txt"
- -- Read the initial contents of the file
- fileContents <- readFile filename
- -- Loop to read the contents of the clipboard and append to the file
- loop fileContents
- where
- loop fileContents = do
- -- Read the contents of the clipboard
- clipboardContents <- readProcess "xclip" ["-o"] ""
- -- Check if the contents of the clipboard are already in the file
- if not (clipboardContents `elem` lines fileContents)
- then do
- -- Append the contents of the clipboard to the file
- appendFile filename (clipboardContents ++ "\n")
- -- Read the updated contents of the file
- updatedFileContents <- readFile filename
- -- Sleep for a specified amount of time before repeating the loop
- threadDelay (10 * 1000000)
- -- Repeat the loop with the updated contents of the file
- loop updatedFileContents
- else do
- -- Sleep for a specified amount of time before repeating the loop
- threadDelay (10 * 1000000)
- -- Repeat the loop with the same contents of the file
- loop fileContents
- 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.
- ----
- Elixir:
- defmodule Clipboard do
- def append_uniquely_to_file do
- # Define the filename
- filename = "output.txt"
- # Read the initial contents of the file
- file_contents = File.read!(filename)
- # Loop to read the contents of the clipboard and append to the file
- loop(file_contents)
- end
- defp loop(file_contents) do
- # Read the contents of the clipboard
- {_, clipboard_contents} = System.cmd("xclip", ["-o"])
- # Check if the contents of the clipboard are already in the file
- if !String.split(file_contents, "\n")
- |> Enum.member?(clipboard_contents) do
- # Append the contents of the clipboard to the file
- File.write!(filename, "#{clipboard_contents}\n", [:append])
- # Read the updated contents of the file
- updated_file_contents = File.read!(filename)
- else
- # Keep the same contents of the file
- updated_file_contents = file_contents
- end
- # Sleep for a specified amount of time before repeating the loop
- :timer.sleep(10_000)
- # Repeat the loop with the updated contents of the file
- loop(updated_file_contents)
- end
- end
- ------
- Erlan:
- -module(clipboard).
- -export([append_uniquely_to_file/0]).
- append_uniquely_to_file() ->
- % Define the filename
- Filename = "output.txt",
- % Read the initial contents of the file
- {ok, FileContents} = file:read_file(Filename),
- % Loop to read the contents of the clipboard and append to the file
- loop(FileContents).
- loop(FileContents) ->
- % Read the contents of the clipboard
- {_, ClipboardContents} = os:cmd("xclip -o"),
- % Check if the contents of the clipboard are already in the file
- case lists:member(ClipboardContents, string:tokens(FileContents, "\n")) of
- true ->
- % Sleep for a specified amount of time before repeating the loop
- timer:sleep(10 * 1000),
- % Repeat the loop with the same contents of the file
- loop(FileContents);
- false ->
- % Append the contents of the clipboard to the file
- file:write_file(Filename, ClipboardContents ++ "\n", [append]),
- % Read the updated contents of the file
- {ok, UpdatedFileContents} = file:read_file(Filename),
- % Sleep for a specified amount of time before repeating the loop
- timer:sleep(10 * 1000),
- % Repeat the loop with the updated contents of the file
- loop(UpdatedFileContents)
- end.
- 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.
- -------
- Rust:
- use std::fs::OpenOptions;
- use std::io::prelude::*;
- use std::time::Duration;
- use std::thread::sleep;
- fn main() {
- let filename = "output.txt";
- loop {
- let clipboard_contents = match get_clipboard_contents() {
- Ok(s) => s,
- Err(e) => {
- eprintln!("Error reading clipboard: {}", e);
- continue;
- }
- };
- if !file_contains_string(filename, &clipboard_contents) {
- match append_to_file(filename, &clipboard_contents) {
- Ok(()) => (),
- Err(e) => eprintln!("Error appending to file: {}", e),
- }
- }
- sleep(Duration::from_millis(10));
- }
- }
- fn get_clipboard_contents() -> Result<String, String> {
- let output = match std::process::Command::new("xclip").arg("-o").output() {
- Ok(o) => o,
- Err(e) => return Err(format!("{}", e)),
- };
- if !output.status.success() {
- return Err(format!("Failed to run xclip: {}", String::from_utf8_lossy(&output.stderr)));
- }
- Ok(String::from_utf8_lossy(&output.stdout).to_string())
- }
- fn file_contains_string(filename: &str, s: &str) -> bool {
- let contents = match std::fs::read_to_string(filename) {
- Ok(c) => c,
- Err(_) => return false,
- };
- contents.contains(s)
- }
- fn append_to_file(filename: &str, s: &str) -> std::io::Result<()> {
- let mut file = OpenOptions::new()
- .write(true)
- .append(true)
- .open(filename)?;
- writeln!(file, "{}", s)
- }
- --------------
- Scala:
- import java.awt.Toolkit
- import java.awt.datatransfer.{Clipboard, StringSeq}
- import scala.concurrent.duration._
- import scala.io.Source
- import scala.concurrent.ExecutionContext.Implicits.global
- import scala.concurrent._
- object ClipboardToFileAppender extends App {
- val filename = "output.txt"
- val sleepDuration = 10.milliseconds
- def getClipboardContents: String = {
- val clipboard = Toolkit.getDefaultToolkit.getSystemClipboard
- val contents = clipboard.getContents(null)
- if (!contents.isDataFlavorSupported(java.awt.datatransfer.DataFlavor.stringFlavor)) ""
- else contents.getTransferData(java.awt.datatransfer.DataFlavor.stringFlavor).asInstanceOf[String]
- }
- def fileContainsString(filename: String, contents: String): Boolean = {
- Source.fromFile(filename).getLines.toList.contains(contents)
- }
- def appendToFile(filename: String, contents: String): Unit = {
- val writer = new java.io.FileWriter(filename, true)
- writer.write(contents + "\n")
- writer.close()
- }
- while (true) {
- val contents = getClipboardContents
- if (!fileContainsString(filename, contents)) {
- appendToFile(filename, contents)
- }
- Thread.sleep(sleepDuration.toMillis)
- }
- }
- -----
- Lisp:
- (defvar *file-name* "output.txt")
- (defvar *sleep-duration* 10)
- (defun get-clipboard-contents ()
- (uiop:run-program "xsel" '("-ob")
- :output :string))
- (defun file-contains-string (file-name string)
- (with-open-file (stream file-name :direction :input)
- (let ((contents (make-string (file-length stream))))
- (read-sequence contents stream)
- (search string contents))))
- (defun append-to-file (file-name string)
- (with-open-file (stream file-name :direction :output
- :if-exists :append)
- (write-string string stream)))
- (loop (let ((contents (get-clipboard-contents)))
- (unless (file-contains-string *file-name* contents)
- (append-to-file *file-name* contents))))
- (sleep *sleep-duration*))
- ----
- Prolog:
- :- use_module(library(socket)).
- :- use_module(library(readutil)).
- sleep(Time) :-
- sleep(Time).
- clipboard_contents(Contents) :-
- process_create(path('xsel'), ['-ob'], [stdout(pipe(Out))]),
- read_stream_to_codes(Out, Codes),
- atom_codes(Contents, Codes).
- file_contains_string(File, String) :-
- open(File, read, Stream),
- read_string(Stream, _, Contents),
- close(Stream),
- sub_string(Contents, _, _, _, String).
- append_to_file(File, String) :-
- open(File, append, Stream),
- write(Stream, String),
- close(Stream).
- loop :-
- clipboard_contents(Contents),
- \+ file_contains_string('output.txt', Contents),
- append_to_file('output.txt', Contents),
- sleep(10),
- loop.
- -------
- Zig:
- const std = @import("std");
- const os = @import("os");
- const io = @import("std").io;
- const FileName = "output.txt".into();
- const SleepDuration = 10s;
- const stdout = io.File.stdout();
- const mem = std.Mem.init();
- const get_clipboard_contents = std.Debug.catchPanic(mem, {
- const process = os.Process.exec("xsel", &["-ob"], .{});
- defer process.close();
- const contents = try process.stdout().readAll().err;
- if (contents) return contents;
- });
- const file_contains_string = std.Debug.catchPanic(mem, {
- var file = try io.File.open(FileName, .{.mode = io.FileOpenMode.read});
- defer file.close();
- var contents = try file.readAll().err;
- if (contents) return contents;
- return try contents.contains(mem, get_clipboard_contents).err;
- });
- const append_to_file = std.Debug.catchPanic(mem, {
- var file = try io.File.open(FileName, .{.mode = io.FileOpenMode.append});
- defer file.close();
- return try file.writeAll(get_clipboard_contents).err;
- });
- const main = std.Debug.catchPanic(mem, {
- while (true) {
- const exists = file_contains_string;
- if (!exists) {
- append_to_file;
- }
- os.Time.sleep(SleepDuration);
- }
- });
- const panic = std.Panic.handle({});
- defer std.Mem.free(mem, panic);
- std.main(main);
- 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.
- ----
- ocaml:
- let clipboard_contents =
- let command = "xsel -ob" in
- let input = Unix.open_process_in command in
- let contents = input_line input in
- let _ = Unix.close_process_in input in
- contents
- let file_contains_string file_name string =
- let file = open_in file_name in
- let rec loop () =
- try
- let line = input_line file in
- if line = string then close_in file;
- true
- with
- End_of_file -> close_in file; false
- in loop ()
- let append_to_file file_name string =
- let file = open_out_gen [Open_wronly; Open_append; Open_creat] 0o644 file_name in
- output_string file (string ^ "\n");
- close_out file
- let rec loop file_name =
- let contents = clipboard_contents in
- let exists = file_contains_string file_name contents in
- if not exists then append_to_file file_name contents;
- Unix.sleep 10;
- loop file_name
- let () = loop "output.txt"
- -----------
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement