深度阅读

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

作者
作者
2023年08月22日
更新时间
9.62 分钟
阅读时间
0
阅读量

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.

相关标签

博客作者

热爱技术,乐于分享,持续学习。专注于Web开发、系统架构设计和人工智能领域。