How to delete a line from a text file in Linux?

Published on Aug. 22, 2023, 12:17 p.m.

To delete a specific line from a text file using Linux command line, you can use the sed command. Here’s an example:

sed -i '2d' file.txt

This command deletes the second line of the file.txt file. The -i option tells sed to edit the file in place, i.e., modify the file directly instead of printing the modified text to standard output.

Alternatively, you can use the awk command to delete a specific line:

awk '{ if (NR != 2) { print } }' file.txt > output_file.txt

This command prints all lines except the second line of the file.txt file to output_file.txt.

Note that you can use different line selection criteria in the sed command, such as range of lines, regular expressions, and more. Consult the sed manual for more options.

Also, be careful when modifying files with these commands, as they may irreversibly delete or modify the file contents. Always make a backup copy of the file before making any changes.

Tags: