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:~$
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:~$
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).
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
nl
is way simpler thanawk
– Jan 05 '20 at 10:13cat -n
is another option, but again, with a slightly different output format (and-n
is non-standard). – Kusalananda Jan 05 '20 at 10:14nl
can't be used to number arbitrary input.nl -ba -d $'\n'
would work with GNUnl
. – Stéphane Chazelas Jan 05 '20 at 10:24