delete all lines with string, process all files in directory

Simply, I have a directory of text files and I need to delete every line in every file containing a specific string. I want to write the modified files to an empty sub directory.

I can't seem to get the sed command to delete the lines containing the string, and not just the string, in other words, not sed '/*string*/d', which doesn't seem to work. I am also not sure how to accumulate the list of input file names and create the output file names. I usually use sed on specific files, so I'm not sure how to process an entire directory. I seem to remember that you can use grep to create a list of filenames, and then process the list, os something like that.

LMHmedchem

string='text pattern'
cd /path/to/files
grep -l  "$string" * |
while read fname 
do
    sed "/$string/d"  $fname > tmp.tmp
    mv tmp.tmp $fname
    mv $fname ./subdirectory/$fname 
done

Start with that.

1 Like

Thanks, the second move command seems redundant. It seems as if the first mv will overwrite the original file, and then the second will move it. I probably want to keep the original file, so it looks like I could just do,
sed "/$string/d" $fname > tmp.tmp
mv tmp.tmp ./subdirectory/$fname

Does that look right?

This one of the lines I am trying to delete,
_D: "trichlormethiazide" "V" 0.683893
where the string is trichlormethiazide

LMHmedchem

---------- Post updated at 04:34 PM ---------- Previous update was at 04:12 PM ----------

That works great, thanks.

Just for clarification, grep is returning only files that contain the value of $string, correct?

Yes. It's returning the names of the files that contain "$string".

No biggie, perhaps, but I would put quotes around $fname (i.e. "$fname" ), should your $string contain spaces..