There are many ways to show line numbers when displaying text files. For example, in this article, we know the utility nl can be used to show line numbers and we also implement a Windows version using C++ (GCC compiler).
In fact, you can use cat -n command to display the contents with the line number.
root@uploadbeta:~# cat --help
Usage: cat [OPTION]... [FILE]...
Concatenate FILE(s), or standard input, to standard output.
-A, --show-all equivalent to -vET
-b, --number-nonblank number nonempty output lines, overrides -n
-e equivalent to -vE
-E, --show-ends display $ at end of each line
-n, --number number all output lines
-s, --squeeze-blank suppress repeated empty output lines
-t equivalent to -vT
-T, --show-tabs display TAB characters as ^I
-u (ignored)
-v, --show-nonprinting use ^ and M- notation, except for LFD and TAB
--help display this help and exit
--version output version information and exit
With no FILE, or when FILE is -, read standard input.
Examples:
cat f - g Output f's contents, then standard input, then g's contents.
cat Copy standard input to standard output.
Report cat bugs to [email protected]
GNU coreutils home page: <http://www.gnu.org/software/coreutils/>
General help using GNU software: <http://www.gnu.org/gethelp/>
For complete documentation, run: info coreutils 'cat invocation'
root@uploadbeta:~#
cat -n can also be used in pipe line.
root@uploadbeta:~# ls -l | cat -n
1 total 4
2 -rw-r--r-- 1 root root 173 Sep 20 00:08 fork.c
root@uploadbeta:~#
We can also use the awk programming to do this rather short.
awk '{ print NR": "$0 }' < file
Or, we can write a BASH script that does the same thing:
#!/bin/bash
# helloacm.com
for filename; do
linecount="1"
while read line
do
echo "${linecount}: $line"
linecount="$(($linecount + 1))"
done < $filename
done
exit 0
You can reverse the lines by using the following tricks:
cat -n filename | sort -rn | cut -c8-
cut -c8- removes the line numbers; sort -rn sorts the text by line numbers in reverse order. This might be useful when displaying a log file in most-recent-to-least-recent order.
–EOF (The Ultimate Computing & Technology Blog) —
432 wordsLast Post: How to Create a Page of Archives (Summary) for All WordPress Posts/Pages using PHP?
Next Post: The Domains and Webhosting History