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.

  • 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

nl is ideally suited:

nl -v2 -p -ba

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

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
1

With pure bash script?

i=2; cat output.txt | while IFS= read -r line; do
    echo "$i $line"
    i=$((i+1))
done
  • That's UUOC, and see also using while loop to process text considered bad practice in shell. – 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 <mygreatfile – Luciano Andress Martini May 25 '16 at 18:22

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.