banner

For a full list of BASHing data blog posts see the index page.     RSS


How to number copy/pasted commands

When I copy commands from a terminal (with or without their outputs) and paste them into a text file or word-processing document, I sometimes want those commands numbered and any output indented. Here's an example, a series of commands as they appear in my terminal:

numbering1

If I highlight those three commands and their output, then middle-click paste into a LibreOffice Writer document (left) or Geany text editor (right), I get this:

numbering2 numbering3

But what I'd like is this:

numbering4 numbering5

This numbering and re-formatting lends itself to what I call a "CoPa" operation, for Copy, Paste. That's a script or function which takes the contents of the primary clipboard (the one loaded when you highlight text) from the xclip utility and does something to the contents before loading them back into xclip for middle-click pasting.

xclip -o | [do something to stdin] | xclip

In this case I use a CoPa function called "fancy" that lives in my .bashrc file:

fancy() { xclip -o | awk '{print /^\$ / ? ++c"\x20\x20\x20"$0 : "\x20\x20\x20\x20\x20"$0}' | xclip; }

To work "fancy" I first highight the lines in my terminal that I want to copy:

numbering6

Then I enter "fancy", which returns me to a new prompt:

numbering7

Now I can paste my numbered and reformatted lines:

numbering8

xclip -o | awk '{print /^\$ / ? ++c"\x20\x20\x20"$0 : "\x20\x20\x20\x20\x20"$0}' | xclip
 
The first command in "fancy" is xclip -o, which sends the contents of the primary clipboard to stdout.
 
The slightly cryptic AWK command is an if/else written "ternary style" and prints each line with a modification. If the line begins with my prompt, which is the "$" character followed by a plain space (/^\$ /), then AWK prints an incremented counter number (++c) followed by 3 spaces followed by the original line ("\x20\x20\x20;"$0 ). Otherwise AWK prints 5 spaces followed by the original line ("\x20\x20\x20\x20\x20"$0).
 
The output from the AWK command is piped to xclip for pasting.
 
I've used the hexadecimal code for a plain space (20) because it's easier to see and count than an invisible space!


Last update: 2020-08-05
The blog posts on this website are licensed under a
Creative Commons Attribution-NonCommercial 4.0 International License