How to delete specific lines from a txt file

I have a Bash script that writes data into a log file, then from that I take out stuff I want using the sed command. That gives me a file data.txt. What I want to know is how I go about deleting specific line inside that data.txt file.

For example:

123
456
789

I want to remove the 2nd line, containing 456 so that I only have

123

789

I tried with sed '2d' data.txt but it doesn't work.

I use this command to create data.txt from log.log:

sed -nE '1s/.{1}(.{2}).*/\1/p;' log.log >> data.txt

Solution 1:

Try this. This should work.

sed -i '2d' data.txt

You have to add -i flag with sed command unless you are redirecting your output to a new file. If you don't add the -i flag, sed will print the pattern space to STDOUT and will not make any changes to the original file.

Automatic backup option

It is quite dangerous to modify a file without taking a proper backup. So sed has its native method to backup a file before editing which is -i.bak option.

So in the above example if we use the backup option, the command would be.

sed -i.bak '2d' data.txt

So it will remove the first line from the file data.txt and will also make a backup copy of the original file with .bak extension.

Solution 2:

You know, besides specifying by line number, you can also do it by matching the content of the line, if that's more useful (which sounds like it might):

sed -i '/^456$/d' data.txt