Search

Adding line numbers to a file

There are multiple ways of adding line numbers to a file, here are a few of them. Please note that none of the methods below modify the original file and to save the output you will have to redirect the output to the required file.

1. nl :

The command nl adds line numbers to the filename passed to it.

nl filename for eg: if we have a file by the name test with the contents



Run the command nl on it as follows



You can add a symbol after the numbers using the options -s



You can explore a few more options of the command in the man pages

2. Using "cat".
cat with the option -n also outputs lines with its line numbers



For eg



3. Using awk

The script below will add line numbers to the test file using an awk script.



4. Using sed

The script below will add line numbers to the test file using a sed script. The "=" command prints the line numbers of line being processed by sed. But only "=" inserts a new line after the line number thus to remove the line number the line and the line number are parsed again through sed using a pipe and the new line character is removed.



5. Using a script

Line number can also be added using a script as shown below

Save the script as num_lines.sh and execute it by passing the file name on the command line as shown below



All the above commands and scripts add line numbers to blank lines too, which might not be required at times. Here are ways of adding line numbers to a file, but not to blank lines

6. Using awk to ignore blank lines

7. Using a script to ignore blank lines

Save the script as num_lines.sh and execute it by passing the file name on the command line as shown below



4 comments: