3

The below command will find all occurances of a string and delete the contents of the files where this string is found.

find / -maxdepth 1 -xdev -type f -exec grep -i "stringtofind" -l {} \; -exec sed -i '/./d' {} \;

I have tried modifying it to just delete the lines where the string is found but can't get it to work.

E.g test file:

blah blah blah
blah blah blah teststring
teststringblah blah blah
blah blah blah

It would delete lines 2 and 3 and leave the file as without gaps between lines:

blah blah blah
blah blah blah
Chris Seymour
  • 83,387
  • 30
  • 160
  • 202
user1166981
  • 1,738
  • 8
  • 26
  • 44

2 Answers2

7

No need for grep here sed -i '/teststring/Id' file deletes all lines in file that contain teststring (case-insensitive) so just combined that with find:

find . -maxdepth 1 -xdev -type f -exec sed -i '/teststring/Id' {} \;

sed demo:

$ cat file
blah blah blah
blah blah blah teststring
teststringblah blah blah
blah blah blah

$ sed '/teststring/Id' file
blah blah blah
blah blah blah
Chris Seymour
  • 83,387
  • 30
  • 160
  • 202
0

You can't edit a file in place with standard script tools. You can create a new file, then replace the old one with the new:

#get a temporary filename
tmp_file_name=$(mktemp)
grep -v teststring $my_file_name > $tmp_file_name
mv $tmp_file_name $myfile_name
A. L. Flanagan
  • 1,162
  • 8
  • 22
  • 1
    yes you can with ed or sed -i or you can code it with awk or.... Alsom you need to quote your variables. As written your script would fail for file name socntainging spaces or globbing characters. – Ed Morton Dec 13 '12 at 14:32
  • Excellent point about quoting variables. Not sure how I missed sed -i since it's in the original problem. For some reason I avoid awk like the plague. – A. L. Flanagan Dec 23 '12 at 13:19
  • You should take another look at awk. It is THE most useful UNIX tool for manipulating text and will let you write the clearest, simplest, most easily maintainable and extensible programs. – Ed Morton Dec 24 '12 at 00:32