cat -n file outputs file with line numbering, but how can I specify at which line to start the numbering? Is there a command that can do that?

I've thought of perhaps splitting the process into a few commands. If I want to start line numbering at line N of the text file file.txt, then:

  1. Print the first N-1 lines, à la head -$((N-1)) file.txt
  2. Print the remaining N lines, numbered: tail -n N file.txt | cat -n

But the second step is not possible if the input is from stdin; the first step will have consumed all of it. I'd have to create some temporary file to read from and then remove it, AFAIK.

1 Answer 1


You can use awk to do this:

awk 'NR >= n { printf("%6d  ", NR-n+1) } 1' n=3

For lines where the current record number (NR) is greater than or equal to n (passed in as a variable), print a line prefix, starting at 1. The 1 at the end is awk short-hand for printing the current line.

You can also still use head(1), as it stops consuming input when it has read the number of lines it needs:

{ head -$((N-1)); cat -n; }

You can pipe into that, or redirect a file:

cat foo | { head -$((N-1)); cat -n; }
{ head -$((N-1)); cat -n; } < foo
  • cat foo | { head -$((N-1)); cat -n; } doesn't seem to work, it only performs the head -$((N-1)) portion of it. The awk solution seems nice, it doesn't work for files with a million or more lines. The "%6d" makes it a tiny bit inflexible, though in reality it will work for most cases.
    – ladaghini
    Nov 15, 2011 at 9:08
  • @ladaghini: works for me. I have head (GNU coreutils) 8.13 (head --version).
    – camh
    Nov 15, 2011 at 9:20
  • @ladaghini: Why does the awk version not work with more than 1 million lines? The result won't be identical to cat -n. Change the printf format to whatever suits you.
    – camh
    Nov 15, 2011 at 9:25
  • The awk solution hard codes the amount of padding, which means the output will not align properly should the number of lines be greater than 999999. The cases are few where the number of lines will be that big, but I'm looking for a "perfect" solution.
    – ladaghini
    Nov 15, 2011 at 11:59
  • My version of head is 8.5. But I don't think that matters much. When I pipe stdin from a command, it doesn't work, but when I redirect a file (using <) it works. They problem lay in the piping it seems.
    – ladaghini
    Nov 15, 2011 at 12:10

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .