Great follow-up question! Beyond cat -n and grep -n, here are a few other common Linux commands that can display line numbers or have specialized line numbering features:
-
nl(number lines): This is a dedicated command for numbering lines. It offers more advanced options for formatting line numbers, like numbering only non-empty lines, inserting a specific separator, or starting the count from a different number.nl /tmp/helloYou'll notice it formats the numbers slightly differently than
cat -n. -
less: When viewing files withless, you can enable line numbers interactively by pressingG(Shift + g) to go to the end of the file, then typing-Nto toggle line numbers on or off. You can also startlessdirectly with line numbers using the-Noption:less -N /tmp/hello -
more: Similar toless,moreis another command for viewing files paginated. Whilemoredoesn't have a direct command-line option for line numbers likeless -N, some older versions or specific configurations might show them, or you might need to combine it withnl. -
vi/vim: These powerful text editors can display line numbers. Insideviorvim, you can type:set nu(for "number") and press Enter to show line numbers. To hide them, use:set nonu. You can also use:set rnufor "relative number" which shows line numbers relative to the cursor position. -
awk:awkis a very versatile text processing language. You can easily add line numbers to its output. The built-in variableNRrepresents the current record (line) number.awk '{print NR, $0}' /tmp/helloThis command prints the line number (
NR) followed by the entire line ($0).
Each of these commands provides line numbering in a slightly different way or for a different purpose, showing the flexibility of Linux tools!
Is there anything else you'd like to explore about them?