Remove Specific Lines From File in Linux

Remove Specific Lines From File in Linux

Linux provides various commands for processing text files. Sometimes we may need to remove specific lines from file. This tutorial shows how to do this in Linux.

Create a new file for testing:

printf "Line1\nLine2\nLine3\nLine4\nLine5\nLine6\nLine7\nLine8\nLine9\nLine10\n" > test.txt

To process text files, we can use sed command. To remove specific line from file, use the nd modifier, where n is a line number. For example, the following command removes 9th line:

sed -i "9d" test.txt

The -i option will edit file in-place.

To remove range of lines starting from m line to n line (including), use m,nd modifier. For example, the following command removes lines from 6 to 8 (including):

sed -i "6,8d" test.txt

The modifiers can be combined. For example, the following command removes lines from 1 to 3 (including) and line 5th:

sed -i "1,3d;5d" test.txt

Leave a Comment

Cancel reply

Your email address will not be published.