1

So I have a range, say 2-4. And I have three lines:

first
second
third

I need my output to be:

2 first
3 second
4 third

I'm trying this on BSD (Mac) awk/sed, which seems to be making it harder.

Charles
  • 80
  • What if you have more than 3 lines ? – don_crissti May 25 '16 at 18:06
  • Ah, I meant the question in a more general sense, in that the range given already matches the amount of lines. So if the range were 2-6 then we'd have 5 lines, etc. – Charles May 25 '16 at 18:14
  • Then there's no point saying "I have a range..." You simply want to number all lines starting from N and that's really trivial... there's a tool that was designed specifically to number lines. – don_crissti May 25 '16 at 18:16
  • Aha, that's true. There's me overcomplicating things again... – Charles May 25 '16 at 18:17

3 Answers3

3

nl is ideally suited:

nl -v2 -p -ba

will start counting from 2 (-v2), ignoring page changes (-p) and numbering all lines (-ba).

Stephen Kitt
  • 434,908
1

POSIXLY:

awk '{printf("%s %s\n", FNR+1, $0)}' file

If you want to pass parameter:

awk -vn=2 '{printf "%s %s\n", n++, $0}' <file

If you want only the range is produced in case the file is longer than the range:

awk -v s=2 -v e=4 'BEGIN{for(n=s;n<=e;n++)print n}' | paste -d' ' - file
cuonglm
  • 153,898
1

With pure bash script?

i=2; cat output.txt | while IFS= read -r line; do
    echo "$i $line"
    i=$((i+1))
done
cuonglm
  • 153,898