How to partially delete content from a file in Linux?

In Linux, we can use the sed command to delete partial content of a file. Sed is a stream editor that can edit files based on specified rules.

Here is an example of using the sed command to delete part of a file’s content:

  1. Remove specific lines:
sed 'N,Md' file.txt

N and M indicate the starting and ending positions of the line numbers that need to be deleted.

  1. Remove the specified characters on a specific line.
sed 'N s/char//g' file.txt

In this case, N represents the line number of the character that needs to be deleted, and “char” represents the character that needs to be deleted.

  1. Remove specified characters from specified lines.
sed '/pattern/s/char//g' file.txt

In this case, “pattern” refers to the pattern of the lines that need to be matched, and “char” refers to the character that needs to be deleted.

  1. Remove lines in the file that contain a specified pattern.
sed '/pattern/d' file.txt

Among them, the pattern is the pattern of the line that needs to be matched.

Please choose the appropriate method of operation as needed.

bannerAds