0

This is example of tr output

user@linux:~$ tr $ '\n' <<< 'abc$def$ghi'
abc
def
ghi
user@linux:~$ 

Would it be possible to add line number to each line?

E.g.

user@linux:~$ tr $ '\n' <<< 'abc$def$ghi'
1. abc
2. def
3. ghi
user@linux:~$ 

2 Answers2

2

You can pipe tr's output into:

awk '{print NR". "$0}'

for instance to get that numbering.

For each input record (records are lines by default), we print the record number (NR) followed by ". " followed by the full record ($0) followed by the output record separator (ORS, newline by default).

cat -n, grep -n '^', nl -ba -d$'\n', pr -t -n are other ways to number lines, but they all give a different output format, not all are portable/standard and some of them (nl, pr) or implementations thereof won't work on arbitrary input as they process some characters or sequences of characters in their input specially.

Note that some awk implementations would also choke on the NUL character if present in the input (can't happen if using the <<< operator in bash though).

0

There is also a nl (number lines) command with many options, originally intended to provide the standard references for editors of publications (don't number blank lines, headers, footers, number by page:line, etc.) Usual standard opts are: nl -ba

Paul_Pedant
  • 8,679
  • cool. nl is way simpler than awk –  Jan 05 '20 at 10:13
  • But it does not give the exact output that the question asks for. cat -n is another option, but again, with a slightly different output format (and -n is non-standard). – Kusalananda Jan 05 '20 at 10:14
  • Note that it's virtually impossible to disable that headers/footers processing portably, so nl can't be used to number arbitrary input. nl -ba -d $'\n' would work with GNU nl. – Stéphane Chazelas Jan 05 '20 at 10:24