To number only the non-empty lines in a file using the cat command, you can combine grep with cat. The grep command can filter out empty lines, and then you can use nl (number lines) or cat -n to number the remaining lines.
Using grep and nl
grep -v '^$' filename.txt | nl
Using grep and cat -n
grep -v '^$' filename.txt | cat -n
Explanation
grep -v '^$' filename.txt: This command filters out empty lines fromfilename.txt. The-voption inverts the match, and'^$'matches empty lines.|: This pipe operator takes the output of thegrepcommand and passes it as input to the next command.nlorcat -n: These commands number the lines of the output fromgrep.
Example
If filename.txt contains:
Line 1
Line 2
Line 3
The output of the above commands would be:
1 Line 1
2 Line 2
3 Line 3
This way, only the non-empty lines are numbered.
