-3

Suppose i have a string = "remove this sentence"

I want to remove this string from all files in the current directory and all files in sub directories of current directory.

How to achieve it?

I have tried this:

sudo grep -rl stringtoreplace ./ | xargs sed -i 'stringtoreplace//g'

It gives me Permission ERROR! even though I am using sudo

string to replace is this:

,"\x3E\x74\x70\x69\x72
  • 1
    Google is your friend: http://stackoverflow.com/questions/1583219/awk-sed-how-to-do-a-recursive-find-replace-of-a-string – Stephen Rauch Feb 16 '17 at 07:13
  • None of it works for me and I don't understand, can You please take my example? – user1735921 Feb 16 '17 at 07:22
  • 2
    Don't use sudo. It's not a panacea for "I don't know what I'm doing so guess harder". Start by trying to change one file in the current directory. Then extend to all files in current directory. Then extend to the full directory tree. See where you get stuck. Read and try the suggestions in the link you've been given. – Chris Davies Feb 16 '17 at 07:39
  • Can you show us the full error message? – andcoz Feb 16 '17 at 08:12

1 Answers1

2
for file in $(find . -mindepth 1 -type f); do sed -i 's/remove\ this\ sentence/stringtoreplace/g' $file; done

Let's break it down.

$(find . -mindepth 1 -type f)

This will find every file starting in working directory, and return it as it's full path. Recursive in that you're searching a minimum depth of one (same directory) or more subdirs deep.

sed -i 's/remove\ this\ sentence/stringtoreplace/g'

-i modify file in-place
/g all occurrences of "remove this sentence" in lines as they're read.

And then there's the "for" loop, which iterates over the files.

Probably easier

Another way this can be done is by:

find . -mindepth 1 -type f -exec sed -i 's/remove\ this\ sentence/stringtoreplace/g' {} \;

...which is the same thing. Here, we're just using find to find the files and execute the sed replace in-place command on each one found.

SYANiDE
  • 507
  • You are right... more atomic to use -exec switch. Also, adjusted answer to reflect closer to requirements, i.e., no strongly-coupled requirement for regular expression. – SYANiDE Feb 17 '17 at 04:17