Find a line in a file and remove it
This solution may not be optimal or pretty, but it works. It reads in an input file line by line, writing each line out to a temporary output file. Whenever it encounters a line that matches what you are looking for, it skips writing that one out. It then renames the output file. I have omitted error handling, closing of readers/writers, etc. from the example. I also assume there is no leading or trailing whitespace in the line you are looking for. Change the code around trim() as needed so you can find a match.
File inputFile = new File("myFile.txt");
File tempFile = new File("myTempFile.txt");
BufferedReader reader = new BufferedReader(new FileReader(inputFile));
BufferedWriter writer = new BufferedWriter(new FileWriter(tempFile));
String lineToRemove = "bbb";
String currentLine;
while((currentLine = reader.readLine()) != null) {
// trim newline when comparing with lineToRemove
String trimmedLine = currentLine.trim();
if(trimmedLine.equals(lineToRemove)) continue;
writer.write(currentLine + System.getProperty("line.separator"));
}
writer.close();
reader.close();
boolean successful = tempFile.renameTo(inputFile);
Bash - find a keyword in a file and delete its line
Use the stream editor, sed:
sed -i ".bak" '/culpa/d' test.txt
The above will delete lines containing culpa in test.txt. It will create a backup of the original (named test.txt.bak) and will modify the original file in-place.
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
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 find a line of code and delete that line from all files in a certain /directory only, using Linux CLI
You can use the following command if you want to remove only the test
pattern of your files instead of deleting the whole line what will in most of the cases break your code:
grep -l -R 'test' /directory | xargs -I {} sed -i.bak 's/test//g' {}
It will replace globally the test pattern by nothing and also take a backup of your files while doing the operations! You never know :-)
If you are sure that you can delete the whole line containing the test
pattern then you can use sed in the following way:
grep -l -R 'test' /directory | xargs -I {} sed -i.bak '/test/d' {}
You can after look for the backup files and delete them if they are not required anymore by using the following command:
find /directory -type f -name '*.bak' -exec rm -i {} \;
You can remove the -i
after the rm
if you do not need confirmation while deleting the files.
How to find and remove line from file in Unix?
Based on your description in your text, here is a cleaned-up version of your sed script that should work.
Assuming a linux GNU sed
sed -i '/abcd=/d' /test.txt
If you're using OS-X, then you need
sed -i "" '/abcd=/d' /test.txt
If these don't work, then use old-school sed
with a conditional mv to manage your tmpfiles.
sed '/abcd=/d' /test.txt > test.txt.$$ && /bin/mv test.txt.$$ test.txt
Notes:
Not sure why you're doing \"/$abcd=/d\"
, you don't need to escape "
chars unless you're doing more with this code than you indicate (like using eval
). Just write it as "/$abcd=/d"
.
Normally you don't need '-e'
If you really want to use '$abcd, then you need to give it a value AND as you're matching the string 'abcd=', then you can do
abcd='abcd='
sed -i "/${abcd}/d" /test.txt
I hope this helps.
Is there a way to remove a whole line in a text file if the word is found in python
Use a condition to check if itemRemove
is in line
or not
with open('CurrentStock.txt', "w") as f:
for line in lines:
if itemRemove not in line:
f.write(line)
Find string and delete line - Node.JS
Let's say we have a text file, shuffle.txt contains the following content
john
doe
user1
some keyword
last word
Now we read the shuffle.txt file and then search for 'user1' keyword. If any line contains the 'user1', then we will remove the line.
var fs = require('fs')
fs.readFile('shuffle.txt', {encoding: 'utf-8'}, function(err, data) {
if (err) throw error;
let dataArray = data.split('\n'); // convert file data in an array
const searchKeyword = 'user1'; // we are looking for a line, contains, key word 'user1' in the file
let lastIndex = -1; // let say, we have not found the keyword
for (let index=0; index<dataArray.length; index++) {
if (dataArray[index].includes(searchKeyword)) { // check if a line contains the 'user1' keyword
lastIndex = index; // found a line includes a 'user1' keyword
break;
}
}
dataArray.splice(lastIndex, 1); // remove the keyword 'user1' from the data Array
// UPDATE FILE WITH NEW DATA
// IN CASE YOU WANT TO UPDATE THE CONTENT IN YOUR FILE
// THIS WILL REMOVE THE LINE CONTAINS 'user1' IN YOUR shuffle.txt FILE
const updatedData = dataArray.join('\n');
fs.writeFile('shuffle.txt', updatedData, (err) => {
if (err) throw err;
console.log ('Successfully updated the file data');
});
});
Here, if a line contains 'user1' keyword, we are removing the entire line. The new shuffle.txt file will be no longer contains a line with 'user1' keyword. The updated shuffle.txt file looks like
john
doe
some keyword
last word
For more information check the doc.
Related Topics
Removing an Element from an Array (Java)
Generate/Get Xpath from Xml Node Java
Sorting a Collection of Objects
How to Check If the User Is Pressing a Key
How to Parse a Mathematical Expression Given as a String and Return a Number
Static Method in a Generic Class
File Path to Resource in Our War/Web-Inf Folder
How to Sort an Arraylist in Java
Why Does Integer Division Code Give the Wrong Answer
How to Avoid "Staleelementreferenceexception" in Selenium
Can You Recommend a Java Library for Reading (And Possibly Writing) CSV Files
Cut Out Image in Shape of Text
How to Import a Class from Default Package
Java and Gui - Where Do Actionlisteners Belong According to MVC Pattern
Java Code for Calculating Leap Year