Move first N lines of output to end without using temporary file

Just copy those lines to the hold buffer (then delete them) and when on last line append the content of hold buffer to pattern space:

some command | sed '1,NUMBER{           # in this range
H                                       # append line to hold space and
1h                                      # overwrite if it's the 1st line
d                                       # then delete the line
}
$G'                                     # on last line append hold buffer content

With gnu sed you could write it as

some command | sed '1,NUMBER{H;1h;d;};$G'

Here's another way with ol' ed (it reads the output of some command into the text buffer and then moves lines 1,NUMBER after the la$t one):

ed -s <<IN
r ! some command
1,NUMBERm$
,p
q
IN

Note that - as pointed out - these will both fail if the output has less than NUMBER+1 lines. A more solid approach would be (gnu sed syntax):

some command | sed '1,NUMBER{H;1h;$!d;${g;q;};};$G'

this one only deletes lines in that range as long as they're not the last line ($!d) - else it overwrites pattern space with hold buffer content (g) and then quits (after printing the current pattern space).


An awk approach:

cmd | awk -v n=3 '
  NR <= n {head = head $0 "\n"; next}
  {print}
  END {printf "%s", head}'

One benefit over @don_crissti's sed approach is that it still works (outputs the lines) if the output has n lines or fewer.


I have xclip and with it this can be done in this way:

./a_command | xclip -in && xclip -o | tail -n +3 && xclip -o | head -n 2

Here is its description:

xclip - command line interface to X selections (clipboard)

NAME
       xclip - command line interface to X selections (clipboard)

SYNOPSIS
       xclip [OPTION] [FILE]...

DESCRIPTION
       Reads from standard in, or from one or more files, and makes the data available as an X selection for pasting into X applications. Prints current X selection to standard out.

       -i, -in
              read text into X selection from standard input or files (default)

       -o, -out
              prints the selection to standard out (generally for piping to a file or program)