Remove lines that contain certain string

sed delete line containing string
sed delete line number
sed delete multiple lines matching pattern
sed delete line after match
sed delete lines matching multiple patterns
sed delete line before match
delete lines containing string vim
sed delete string from line

I'm trying to read a text from a text file, read lines, delete lines that contain specific string (in this case 'bad' and 'naughty'). The code I wrote goes like this:

infile = file('./oldfile.txt')

newopen = open('./newfile.txt', 'w')
for line in infile :

    if 'bad' in line:
        line = line.replace('.' , '')
    if 'naughty' in line:
        line = line.replace('.', '')
    else:
        newopen.write(line)

newopen.close()

I wrote like this but it doesn't work out.

One thing important is, if the content of the text was like this:

good baby
bad boy
good boy
normal boy

I don't want the output to have empty lines. so not like:

good baby

good boy
normal boy

but like this:

good baby
good boy
normal boy

What should I edit from my code on the above?

You can make your code simpler and more readable like this

bad_words = ['bad', 'naughty']

with open('oldfile.txt') as oldfile, open('newfile.txt', 'w') as newfile:
    for line in oldfile:
        if not any(bad_word in line for bad_word in bad_words):
            newfile.write(line)

using a Context Manager and any.

Remove line containing certain string and the following line, If you have GNU sed (so non-embedded Linux or Cygwin): sed '/bar/,+1 d'. If you have bar on two consecutive lines, this will delete the second line without� To remove all lines containing a particular string in the vi or Vim text editors, you can use the g command to globally search for the specified string and then, by putting a "d" at the end of the command line, specify that you want all lines containing the specified string deleted. E.g., If I wanted to remove all lines containing the string

You could simply not include the line into the new file instead of doing replace.

for line in infile :
     if 'bad' not in line and 'naughty' not in line:
            newopen.write(line)

Remove Lines Containing, Best Online Tool to Remove Lines Containing Text or String. This will remove line Containing from provided text or input string, however keep Here is a Text:. I would like to exclude lines containing a string "REVERSE", but my lines do not match exactly with the word, just contain it. My input data frame: Value Name 55 REVERSE223 22 GENJJS 33 REVERSE456 44 GENJKI My expected output: Value Name 22 GENJJS 44 GENJKI

I have used this to remove unwanted words from text files:

bad_words = ['abc', 'def', 'ghi', 'jkl']

with open('List of words.txt') as badfile, open('Clean list of words.txt', 'w') as cleanfile:
    for line in badfile:
        clean = True
        for word in bad_words:
            if word in line:
                clean = False
        if clean == True:
            cleanfile.write(line)

Or to do the same for all files in a directory:

import os

bad_words = ['abc', 'def', 'ghi', 'jkl']

for root, dirs, files in os.walk(".", topdown = True):
    for file in files:
        if '.txt' in file:
            with open(file) as filename, open('clean '+file, 'w') as cleanfile:
                for line in filename:
                    clean = True
                    for word in bad_words:
                        if word in line:
                            clean = False
                    if clean == True:
                        cleanfile.write(line)

I'm sure there must be a more elegant way to do it, but this did what I wanted it to.

How to Remove Lines Containing a Word or String in a Text File , Method 1: Remove lines using Bookmark feature in Notepad++. Open the text- based file using Notepad++; Press Ctrl + F to open the Find and Replace dialog. If you have hundreds of lines in a text file and want to bulk delete lines that contain a word or string, this article is for you. Let's use the excellent third-party text editor Notepad++ (free) for deleting lines containing a word in a text-based file, using different methods. Remove Lines Containing a Word, Phrase

The else is only connected to the last if. You want elif:

if 'bad' in line:
    pass
elif 'naughty' in line:
    pass
else:
    newopen.write(line)

Also note that I removed the line substitution, as you don't write those lines anyway.

Delete all lines containing a pattern | Vim Tips Wiki, Delete all lines containing a pattern. The ex command g is very useful for acting on lines that match a pattern. You can use it with the d command, to delete all lines that contain a particular pattern, or all lines that do not contain a pattern. The ex command g is very useful for acting on lines that match a pattern. You can use it with the d command, to delete all lines that contain a particular pattern, or all lines that do not contain a pattern. For example, to delete all lines containing "profile" (remove the/d to show the lines that the command will delete)::g/profile/d

Today I needed to accomplish a similar task so I wrote up a gist to accomplish the task based on some research I did. I hope that someone will find this useful!

import os

os.system('cls' if os.name == 'nt' else 'clear')

oldfile = raw_input('{*} Enter the file (with extension) you would like to strip domains from: ')
newfile = raw_input('{*} Enter the name of the file (with extension) you would like me to save: ')

emailDomains = ['windstream.net', 'mail.com', 'google.com', 'web.de', 'email', 'yandex.ru', 'ymail', 'mail.eu', 'mail.bg', 'comcast.net', 'yahoo', 'Yahoo', 'gmail', 'Gmail', 'GMAIL', 'hotmail', 'comcast', 'bellsouth.net', 'verizon.net', 'att.net', 'roadrunner.com', 'charter.net', 'mail.ru', '@live', 'icloud', '@aol', 'facebook', 'outlook', 'myspace', 'rocketmail']

print "\n[*] This script will remove records that contain the following strings: \n\n", emailDomains

raw_input("\n[!] Press any key to start...\n")

linecounter = 0

with open(oldfile) as oFile, open(newfile, 'w') as nFile:
    for line in oFile:
        if not any(domain in line for domain in emailDomains):
            nFile.write(line)
            linecounter = linecounter + 1
            print '[*] - {%s} Writing verified record to %s ---{ %s' % (linecounter, newfile, line)

print '[*] === COMPLETE === [*]'
print '[*] %s was saved' % newfile
print '[*] There are %s records in your saved file.' % linecounter

Link to Gist: emailStripper.py

Best, Az

Remove Lines Containing… – Text Mechanic, e.g. Enter the word "text" to remove lines containing the word "text". Click the " Remove Lines Containing" button and all lines containing your specified search � Remove Letter Accents; Remove Lines Containing… Remove Punctuation; Sort Text Lines; Format Tools. ASCII to Unicode Converter; Convert Timestamp (Unix) Obfuscation Tools. Binary Code Translator; Disemvowel Tool; Encryption Generator; Reverse Text Generator; ROT13 Caesar Cipher; Word Scrambler / Descrambler; Randomization Tools. Random Line

Unix Sed Command to Delete Lines in File, 13. Delete lines that contain a pattern > sed '/debian/d' file linux unix fedora ubuntu 14. Delete lines starting from a pattern till the last line I have a very large data frame in python and I want to drop all rows that have a particular string inside a particular column. For example, I want to drop all rows which have the string "XYZ" as a substring in the column C of the data frame. Can this be implemented in an efficient way using .drop() method?

Delete Lines in a Text File That Contain a Specific String, Learn how to use grep, awk, and sed to delete lines containing a specific string from text files in Linux. Remove Certain Rows Containing Certain Data with VBA In the developer tab, go to Visual Basic as normal and create a module like the one below. Change and amend the code to your needs and then simply run the module on your sheet.

Notepad++ : How to remove all lines containing a specific string text , Notepad++ : How to remove all lines containing a specific string text In this video tutorial , I Duration: 4:30 Posted: Dec 16, 2015 SED is an Stream Editor having capability to remove lines from file having specific string. Using -i with sed we can remove line in same file. Example 1: Remove all lines from /var/log/messages having string “DELETE THIS TEXT” and restore output in new file. Do not make any changes in original line.

Comments
  • Why are you replacing dots with spaces in lines you want to ignore anyway?
  • @Wooble Maybe OP expects that to be a regular expression, where he would replace all occurrences of anything in line with nothing.
  • i think you want "or" instead of "and"
  • i want the lines that only contains one of bad or naghuty to be deleted too. which one is right..?
  • @H.Choi It's either not ('bad' in line or 'naughty' in line) or not 'bad' in line and not 'naughty' in line, so and here should be correct.
  • Won't work if there's something like this is bad! in the input file.