How to Delete Specific Strings from a File

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 string in a text file?

Locate the file.

File file = new File("/path/to/file.txt");

Create a temporary file (otherwise you've to read everything into Java's memory first).

File temp = File.createTempFile("file", ".txt", file.getParentFile());

Determine the charset.

String charset = "UTF-8";

Determine the string you'd like to delete.

String delete = "foo";

Open the file for reading.

BufferedReader reader = new BufferedReader(new InputStreamReader(new FileInputStream(file), charset));

Open the temp file for writing.

PrintWriter writer = new PrintWriter(new OutputStreamWriter(new FileOutputStream(temp), charset));

Read the file line by line.

for (String line; (line = reader.readLine()) != null;) {
// ...
}

Delete the string from the line.

    line = line.replace(delete, "");

Write it to temp file.

    writer.println(line);

Close the reader and writer (preferably in the finally block).

reader.close();
writer.close();

Delete the file.

file.delete();

Rename the temp file.

temp.renameTo(file);

See also:

  • The Java Tutorials - Lesson: basic I/O

Remove occurrences of string in text file

sed -i -e 's/goodbye//g' filename

To delete multiple words:

sed -i -e 's/\(goodbye\|hello\|test\|download\)//g' filename

Remove string from txt file

Read the text file get the content in a variable then use String.replace

For example

var stringContent="Here goes the content of the textFile after read"
var res=stringContent.replace('string3','');
//write back res to the file or do what ever

Python: Remove first instance only of string from text file

If I've understood your question correctly then you want to get rid of first '1.' and keep the rest. It can be done in multiple ways, like below code.

with open('infile.txt', 'r') as f:
lines = f.readlines()
with open('outfile.txt', 'w+') as f:
t = '1.'
for line in lines:
line = line.strip("\n")
if line != "Desired text on line to remove" and line != t:
f.write(line)
f.write("\n")
if line == t:
t = None

One of them is by simply using logical operators (which I've used) and create a variable you want to remove. Which in my case as t. Now use it to filter the first instance. Thereafter change its value to None so that in the next instance it will always be a True statement and the condition to run or not depends on if line is equal to our desired text or not.

P.S.- I've added some more line of codes like line = line.strip("\n") and f.write("\n") just to make the output and code clearer. You can remove it if you want as they don't contribute to clear the hurdle.

Moreover, if you don't get the desired output or my code is wrong. Feel free to point it out as I've not written any answers yet and still learning.

Delete a specific string from a list of strings in a file python

You can just process lines you have read into memory and write them to the file (replacing it's content):

name = input("Insert the name you want to delete: ")
# let's strip excessive whitespace and change to lower case:
name = name.strip().lower()
book = "data.txt"

# use 'with' construct to ensure that file is closed after use:
with open(book, 'r') as f:
lines = f.read().splitlines()

filtered = []
for line in lines:
try: # guard against incorrect record, e.g. 'Guido, 1956'
name_, sex, year = line.split(',')
except ValueError:
print("cannot unpack this line:", line)
continue
if name == name_.strip().lower():
continue # we don't want this line, so we skip it
filtered.append(line) # line is ok, we keep it

# join list of lines into one string and write to the file:
with open(book, 'w') as f:
f.write('\n'.join(filtered))


Related Topics



Leave a reply



Submit