AWK command and sed command are great text processing commands. They support a wealth of command options, conditional judgments, and loop functions.
This article will use these capabilities to show you how to delete specified line number(s) from a text file.
The following is the test content used this time, we will use this file to test how to delete a specific line number(s).
1: This is a test file. 2: Use the awk command NR variable to delete a specific line 3: Use the sed command action option d to delete a specific line 4: Awk command supports condition judgment 5: awk command supports loop function 6: The sed command has rich action options: a, d, g …
Use the sed command to remove specific line number(s)
In the following example, we will use the sed command action option “d” to delete the specified line number(s) of the text file.
Delete the first to fourth lines of the file using sed
➜ ~ sed '1,4d' test.txt
Delete the first and fourth lines of the file using sed
➜ ~ sed '1d;4d;' test.txt
If you want to back up the original file contents when using the sed command to delete specific lines, you can use the following command statement:
➜ ~ sed -i "_bak" '1d;4d;' test.txt
Use the awk command to remove specific line number(s)
In the following example, we will use the awk NR variable (file line number) to delete a specific line number(s).
Delete the first to fourth lines of the file using awk
➜ ~ awk '{if(NR>4) {print $0}}' test.txt
Delete the first and fourth lines of the file using awk
➜ ~ awk '{if(NR!=1 && NR!=4){print $0}}' test.txt