How to number non-empty lines?

0103

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 from filename.txt. The -v option inverts the match, and '^$' matches empty lines.
  • |: This pipe operator takes the output of the grep command and passes it as input to the next command.
  • nl or cat -n: These commands number the lines of the output from grep.

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.

0 Comments

no data
Be the first to share your comment!