Command line copy & paste

I needed a way to copy a lot of text through a shell and couldn’t find an easy way to do it through the command line:
Now I can copy & paste like so:
cat 1.txt | copy

and on another shell:
paste | grep “test”

N.b. the copy program has to remain running to be able to paste text, I believe this is common to all Linux applications which provide clipboard functionality. As far as I am aware there is no specific memory set aside for a clipboard, so it is down to individual programs to provide this memory.

Compile the Copy.c file with:

gcc -I/usr/lib:. -lpthread -lgthread-2.0 -g -Wall Copy.c -o copy `pkg-config –cflags gtk+-2.0 gthread-2.0` `pkg-config –libs gtk+-2.0 gthread-2.0

Copy.c:

#include <gtk/gtk.h>
#include <gdk/gdk.h>
#include <glib.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <stdio.h>
#include <errno.h>
#include <string.h>


int main( int   argc,  char *argv[] )
{
        GtkWidget *window;
        gtk_init (&argc, &argv);
        window = gtk_window_new (GTK_WINDOW_TOPLEVEL);

        GString* gstr = g_string_new (NULL);
        GtkClipboard* clip = gtk_clipboard_get(NULL);

        int c;
        while((c = fgetc(stdin)) != EOF){
                printf("%c",c);
                g_string_append_printf (gstr,"%c",c);
        }

        gtk_clipboard_set_text(clip,g_string_free(gstr,FALSE),-1);
        gtk_main (); // infinite loop
        return 0;
}

Paste.c

#include <gtk/gtk.h>
#include <gdk/gdk.h>
#include <glib.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <stdio.h>
#include <errno.h>
#include <string.h>


int main( int   argc,  char *argv[] )
{
        GtkWidget *window;
        gtk_init (&argc, &argv);
        window = gtk_window_new (GTK_WINDOW_TOPLEVEL);

        GString* gstr = g_string_new (NULL);
        GtkClipboard* clip = gtk_clipboard_get(NULL);
        printf("%s",gtk_clipboard_wait_for_text(clip));

        return 0;
}

Advertisements

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: