-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
4
  • 1
    Google is your friend: stackoverflow.com/questions/1583219/… Feb 16, 2017 at 7:13
  • None of it works for me and I don't understand, can You please take my example? Feb 16, 2017 at 7: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.
    – roaima
    Feb 16, 2017 at 7:39
  • Can you show us the full error message?
    – andcoz
    Feb 16, 2017 at 8:12

1 Answer 1

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.

2
  • 2
    1. Don't loop over find's output 2. What is the point of using sed with -r here when you don't even know if it's needed ? Feb 16, 2017 at 11:21
  • 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, 2017 at 4:17

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.