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
  • 7
  • 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 `n`umber `l`ines. – 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
  • 411,918
  • 54
  • 1,065
  • 1,164
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
  • 150,973
  • 38
  • 327
  • 406
1

With pure bash script?

i=2; cat output.txt | while IFS= read -r line; do
    echo "$i $line"
    i=$((i+1))
done
cuonglm
  • 150,973
  • 38
  • 327
  • 406
Luciano Andress Martini
  • 6,490
  • 4
  • 26
  • 56
  • That's [UUOC](https://en.wikipedia.org/wiki/Cat_(Unix)#Useless_use_of_cat), and see also [using while loop to process text considered bad practice in shell](http://unix.stackexchange.com/q/169716/38906). – cuonglm May 25 '16 at 18:18
  • 1
    In some limited Linux shells you will must need to use loops to process text, because you will not have any other tools. I now the cat is not necessary, is just an example to be replace with the very specific command the user are executing... But if there is really a output.txt file, they can use something like while ; bla; done – Luciano Andress Martini May 25 '16 at 18:22