If you need to remove the first N lines from a text file in Linux, you can use the sed command, which is a powerful text editor that allows you to manipulate text files from the command line. In this article, we’ll explore how to use sed to delete the first N lines from a text file in Linux.
Step 1: Check the contents of the file
Before you delete the first N lines from a text file, it’s a good idea to check the contents of the file to ensure that you’re deleting the correct lines. You can use the head command to display the first N lines of the file. For example, if you want to view the first 10 lines of a file called “file.txt”, you can use the following command:
head -n 10 file.txt
This will display the first 10 lines of the file on the screen.
Step 2: Delete the first N lines using sed
Once you’ve verified that you want to delete the first N lines of the file, you can use the sed command to do so. The basic syntax for using sed to delete lines is as follows:
1 | sed 'Nd' filename |
In this command, N is the number of the line you want to delete, and filename is the name of the file you want to modify. The ‘d’ at the end of the command tells sed to delete the specified line.
To delete the first 10 lines of a file called “file.txt”, you can use the following command:
sed '1,10d' file.txt
This command will delete the first 10 lines of the file and display the modified file on the screen. If you want to modify the file directly, you can use the -i option, like this:
sed -i '1,10d' file.txt
This command will delete the first 10 lines of the file and save the changes to the file.
Step 3: Verify that the lines were deleted
After you’ve used sed to delete the first N lines of the file, you can verify that the lines were deleted by using the head command again:
head -n 10 file.txt
This command will display the first 10 lines of the modified file on the screen. If the lines were successfully deleted, the first line displayed should be the line that was originally the (N+1)th line of the file.
Conclusion
In this article, we’ve explored how to delete the first N lines of a text file in Linux using the sed command. By using the sed command with the appropriate syntax, you can quickly and easily delete lines from a text file from the command line. Remember to verify the contents of the file before you delete any lines to avoid accidentally deleting the wrong lines.