-3

My text is:

Hi
Bye
Nope
Sorry
Cya
Chill

How can I make it:

[1] Hi
[2] Bye
[3] Nope

and so on and so forth?

closed as unclear what you're asking by Anthon, Stephen Rauch, Anthony Geoghegan, Rui F Ribeiro, hildred Jul 3 '17 at 17:00

Please clarify your specific problem or add additional details to highlight exactly what you need. As it's currently written, it’s hard to tell exactly what you're asking. See the How to Ask page for help clarifying this question. If this question can be reworded to fit the rules in the help center, please edit the question.

  • 1
    Try cat filename | nl – Amit24x7 Jul 3 '17 at 14:42
  • 2
    What you show is not just adding line numbers, you skip empty lines for numbering, and wrap the output to a single line. Please edit your post to make it more clear what you want. – Anthon Jul 3 '17 at 14:44
6

The nl ("number lines") utility does this:

$ cat file
Hi
Bye

Nope
Sorry

Cya
Chill

$ nl file
     1  Hi
     2  Bye

     3  Nope
     4  Sorry

     5  Cya
     6  Chill

There are a number of options to nl that you can play around with. It also does page numbering etc.

Some implementations of cat also supports line numbering:

$ cat -n file
     1  Hi
     2  Bye
     3
     4  Nope
     5  Sorry
     6
     7  Cya
     8  Chill

With awk:

$ awk '{ print NR, $0 }' file
1 Hi
2 Bye
3
4 Nope
5 Sorry
6
7 Cya
8 Chill

Or, if you don't want numbering of blank lines:

$ awk '$0 { print ++nr, $0; next } { print }' file
1 Hi
2 Bye

3 Nope
4 Sorry

5 Cya
6 Chill

With awk, it's also easy to do special formatting:

$ awk -vOFS="\t" '$0 { print "[" ++nr "]", $0; next } { print }' file
[1]     Hi
[2]     Bye

[3]     Nope
[4]     Sorry

[5]     Cya
[6]     Chill

Or...

$ awk -vOFS=":\t" '$0 { printf("[%03d]%s%s\n", ++nr, OFS, $0); next } { print }' file
[001]:  Hi
[002]:  Bye

[003]:  Nope
[004]:  Sorry

[005]:  Cya
[006]:  Chill

From the paste manual (on OpenBSD):

$ sed '=' file | paste -s -d '\t\n' - -
1       Hi
2       Bye
3
4       Nope
5       Sorry
6
7       Cya
8       Chill
1

awk '{printf "%s.\t%s\n",NR,$0}' file

Additionally you can just use the nl command. So like:

cat /path/to/file | nl > /path/to/output

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