The Computer Oracle

Finding and deleting lines from all files recursively

--------------------------------------------------
Rise to the top 3% as a developer or hire one of them at Toptal: https://topt.al/25cXVn
--------------------------------------------------

Music by Eric Matyas
https://www.soundimage.org
Track title: Puzzle Game 3

--

Chapters
00:00 Finding And Deleting Lines From All Files Recursively
00:29 Accepted Answer Score 29
01:37 Answer 2 Score 2
01:57 Answer 3 Score 0
02:17 Thank you

--

Full question
https://superuser.com/questions/445514/f...

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#grep #sed

#avk47



ACCEPTED ANSWER

Score 29


With a GNU sed:

find . -type f -print0 | xargs -0 sed -i /KeyWord/d

With an OSX sed:

find . -type f -print0 | xargs -0 sed -i '' /KeyWord/d

First command find finds all the standard files (not directories, or pipes, or etc.), prints them separated by \0 (so filenames can contains spaces, newlines, etc.).

Second command xargs reads the output of find, grabs a list based on a separator (\0 because of -0), invokes sed -i [...] with added parameters from the list (sed will be called multiple times if there are a lot of files, as the maximum length of the parameters is limited in each invocation).

The sed command modifies in-place (-i).

As to /KeyWord/d, it'll delete lines containing the regular expression KeyWord.

You should learn sed to properly understand the (simple but unusual) syntax, and refer to the appropriate manpages for more information about the tools involved here.


And as I like to promote zsh, the solution with its extended globs:

sed -i /KeyWord/d **/*(.)



ANSWER 2

Score 2


You can use Vim in Ex mode:

find -type f -exec ex -sc g/KeyWord/d -cx {} ';'
  1. g global search

  2. d delete

  3. x save and close




ANSWER 3

Score 0


I originally started with a grep to find the files, so it feels a little safer to modify that slightly than to switch to a find.

$ grep -l -r KeyWord * | xargs sed -i /KeyWord/d

grep -l will print the filenames, sed -i will edit them.