Delete specific line number(s) from a text file using sed?
If you want to delete lines from 5 through 10 and line 12th:
sed -e '5,10d;12d' file
This will print the results to the screen. If you want to save the results to the same file:
sed -i.bak -e '5,10d;12d' file
This will store the unmodified file as file.bak
, and delete the given lines.
Note: Line numbers start at 1. The first line of the file is 1, not 0.
How to delete a specific line in a file?
First, open the file and get all your lines from the file. Then reopen the file in write mode and write your lines back, except for the line you want to delete:
with open("yourfile.txt", "r") as f:
lines = f.readlines()
with open("yourfile.txt", "w") as f:
for line in lines:
if line.strip("\n") != "nickname_to_delete":
f.write(line)
You need to strip("\n")
the newline character in the comparison because if your file doesn't end with a newline character the very last line
won't either.
How to delete from a text file, all lines that contain a specific string?
To remove the line and print the output to standard out:
sed '/pattern to match/d' ./infile
To directly modify the file – does not work with BSD sed:
sed -i '/pattern to match/d' ./infile
Same, but for BSD sed (Mac OS X and FreeBSD) – does not work with GNU sed:
sed -i '' '/pattern to match/d' ./infile
To directly modify the file (and create a backup) – works with BSD and GNU sed:
sed -i.bak '/pattern to match/d' ./infile
Deleting specific line from file
Try this:
line.replace(line.find(deleteline),deleteline.length(),"");
Delete and replace a Specific Line in .txt file
Here is a working example of what you want to do: it increments the number of likes for a movie. It does not store the contents of the whole file into the buffer. The file might be of a large size, so it might not be very efficient.
#include <fstream>
#include <iostream>
#include <string>
int main()
{
std::fstream fileMovies{"sample.txt",
std::ios_base::in | std::ios_base::out | std::ios_base::binary};
if (!fileMovies.is_open())
{
std::cerr << "Failed to open file" << std::endl;
return -1;
}
std::string movieName{};
std::getline(std::cin, movieName);
std::string line{};
line.reserve(256);
long long int pos = fileMovies.tellp();
for (line; std::getline(fileMovies, line);)
{
if (line.find(movieName) != std::string::npos)
break;
line.clear();
pos = fileMovies.tellp();
}
if (fileMovies.eof())
{
std::cerr << "Failed to find the movie by name" << std::endl;
return -1;
}
long long int curPos = fileMovies.tellp();
// TODO: check format
long long int commaPos = line.rfind(',');
fileMovies.seekp(pos + commaPos + 2);
int liked = 0;
fileMovies >> liked;
fileMovies.seekp(pos + commaPos + 2);
fileMovies << ++liked;
return 0;
}
Output:
PS C:\dev\builds\editfile\Release-Visual Studio\bin> cat .\sample.txt
SNO, Name, NoOfPeopleLiked
1, The Shawshank Redemption, 77
2, The Godfather, 20
3, Into The Wild, 35
4, The Dark Knight, 55
5, 12 Angry Men, 44
6, Schindler's List, 33
7, The Lord of the Rings: The Return of the King, 25
8, Pulp Fiction, 23
9, The Good, the Bad and the Ugly, 32
10, The Lord of the Rings: The Fellowship of the Ring, 56
PS C:\dev\builds\editfile\Release-Visual Studio\bin> .\main.exe
Angry
PS C:\dev\builds\editfile\Release-Visual Studio\bin> cat .\sample.txt
SNO, Name, NoOfPeopleLiked
1, The Shawshank Redemption, 77
2, The Godfather, 20
3, Into The Wild, 35
4, The Dark Knight, 55
5, 12 Angry Men, 45
6, Schindler's List, 33
7, The Lord of the Rings: The Return of the King, 25
8, Pulp Fiction, 23
9, The Good, the Bad and the Ugly, 32
10, The Lord of the Rings: The Fellowship of the Ring, 56
Keep in mind, that you can't append new characters in the middle of the file (nor can you erase them). You can only overwrite the existing ones at the current position.
So in order for this to work properly, you should use the number of likes with trailing spaces, or in format like 0045
.
Also, pay attention that you have to use std::fstream
with flags in | out | binary
. Binary is necessary in order to properly count the current position.
How to delete a specific line in a text file in c++
Currently you delete only the first occurrence of deleteline
in each line. To delete the whole line starting with deleteline
you have to replace
line.replace(line.find(deleteline), deleteline.length(), "");
temp << line << endl;
with
std::string id(line.begin(), line.begin() + line.find(" "));
if (id != deleteline)
temp << line << endl;
Delete specific line from text file
Why is not the line removed?
https://docs.oracle.com/javase/8/docs/api/java/util/ArrayList.html
E remove(int index)
Removes the element at the specified position in this list.boolean remove(Object o)
Removes the first occurrence of the specified element from this list, if it is present.
Since Integer line
is Object
and not a primitive data type int
, this call
filecontent.remove(line);
tries to remove the line with a content equal to new Integer(1)
.
Change the method argument to int line
or add type cast to the call filecontent.remove((int) line)
.
Why is an empty line added?
The extra space is added by this statement:
String textToAppend = "\r\n" + filecontent.get(i);
Change it like this:
String textToAppend = filecontent.get(i) + "\r\n";
Related Topics
Has the New C++11 Member Initialization Feature at Declaration Made Initialization Lists Obsolete
Can MACros Be Overloaded by Number of Arguments
How to Copy Contents of a Directory into Build Directory After Make with Cmake
Detailed Guide on Using Gcov with Cmake/Cdash
What Is a Good Oo C++ Wrapper for SQLite
What Does the Fpermissive Flag Do
Cleaning Up an Stl List/Vector of Pointers
Netbeans 7.2 Shows "Unable to Resolve Identifier" , Although Build Is Successful
How to Create a Simple Qt Console Application in C++
Has Anyone Ever Had a Use for the _Counter_ Pre-Processor MACro
Need to Call a Function at Periodic Time Intervals in C++
Slot Is Being Called Multiple Times Every Time a Signal Is Emitted
Passing End of Transmission (Ctrl + D) Character in Eclipse Cdt Console
Difference in Behavior While Using Dynamic_Cast with Reference and Pointers