Sometimes, we end up in a situation where there is a need to print or delete specific set of lines from a file. I’m providing the commands to print/delete the lines by line number, line length or blank lines
We will be using the file with below content for trying the commands,
Printing a range of lines based on line numbers:
sed -n ‘linenum1,linenum2p’ <file_name>
The below example shows the command that prints from 2nd line through 3rd line of the file test.txt
Deleting a range of lines based on line numbers:
sed ‘linenum1,linenum2d’ <file_name>
This command displays the output of the file after removal of the said range. Below example shows the same. However, the file test.txt will not be modified. This is just a result that shows how a file would look if the said lines have been removed.
To save the file instead of printing the output post the removal of the line numbers mentioned in the command, below command can be executed.
sed -i ‘linenum1,linenum2d’ <file_name>
Printing the lines those exceed a specific length:
awk ‘{print NR,$0}’ <file_name>|awk ‘length>14’
The above command would print the lines those are having the length more than 13 character bytes. The below example would help understand this more.
Deletion of blank lines:
The blank lines or lines with no content in it can be deleted by using the sed command in below format,
sed /^$/d <file_name>
The below example prints the output of the file test.txt without the blank lines-line no. 11, 12, 13. Please refer “Sample File — test.txt” that shows the blank lines.
However, this just prints the output of the file with the blank lines removed but the modified output will not be saved.
To save the file with these modifications instead of printing the output, the below command can be used.
sed -i /^$/d <file_name>
All the above commands showed can be modified and used according to the slight changes in the requirement.