More on displaying files with head

That was fun! Since my previous entry on using head to display the contents of several files in a form that's easy to cut and paste, multiple people have sent elaborations or related tricks. It seemed like it would be a good idea to post a roundup, since I learned a bunch.

Multiple people (I think Josh Triplett was the first) pointed out that one can avoid having to pick a sufficiently large value of -n by instead using:

    head -n -0 *.install

With GNU head at least, a negative number says to print out all lines of the file except that many at the end, so -0 displays the whole file, regardless of size. Unfortunately, while this works anywhere that I am likely to run it, it's not specified by POSIX, while the original is.

Another variation, pointed out by Buck Huppmann, is:

    tail -n +0 *.install

The +0 syntax is required by POSIX, unlike the -0 syntax for head... but unfortunately POSIX doesn't require that tail supports multiple files and the headers, although it does for head.

Buck also pointed out that including the -v flag will always force the header even if there's only one file, which is useful. (Although be warned that -v isn't a POSIX-recognized flag.)

Markus Raab also pointed out the xsel utility, which I'd heard of but hadn't ever used. If the goal is to cut and paste the output, using:

    head -v -n -0 *.install | xsel -i

avoids the cut part by dumping the result directly into the X selection. Buck pointed out xclip, which does the same thing. Both can be used with the -o flag inside an editor to paste as well if you don't want to reach for a mouse. In vi :r !xclip -o, and in Emacs, C-u M-! xclip -o.

Finally, Guillem Jover metioned that:

    grep . *.install

does sort of the same thing with a different output format that may be more useful depending on what you're doing. (I find it less human-readable but more machine-parsable.)

Posted: 2014-01-04 20:38 — Why no comments?

Last spun 2022-02-06 from thread modified 2014-01-05