0

Presuming there is a folder with the name "my-folder" which contains 100 files. If we want to replace (not in the filename, but in actual files) in all 100 files the string "originalString" with "replacedString" what command should do the job?

Tried:
grep -rl matchstring ~/my-folder | xargs sed -i 's/originalString/replacedString/g'

find ~/my-folder -type f -exec sed -i 's/originalString/replacedString/g' {} \;

I've also read this on stackoverflow.

None of these work for me. I am spelling something wrong? Btw I am on linux.

2
  • both solutions seem fine to me. Isn't it working at all or to what extend? Commented Jul 17, 2015 at 12:49
  • grep -rl matchstring ~/my-folder | xargs sed -i 's/originalString/replacedString/g' gives me sed: no input files and the second command doesent gives me anything. Could it be because in the directory I provide, there are another directories in which the files are? Commented Jul 17, 2015 at 12:55

1 Answer 1

5

I would use this:

find my_folder -type f -exec sed 's/old_string/new_string/g' {} +

Once you can confirm it is working, pass the -i option to sed to make it edit the original files in place.

This is (very) close to your second solution, however I'm using the + instead of \; as the ending delimiter of find's exec option. This works the like xargs - the command line is built by appending each selected file name. At the end, the total number of invocations of the command will be much less than the number of matched file.

Sign up to request clarification or add additional context in comments.

5 Comments

This gives me: find: Arguments to -type should contain only one letter
Forgive me, I've forgotten the f. Edited that.
@Christian I need to join a meeting now, being back in ~30min.
thank you so much! It worked. find myFolder -type f -exec sed -i 's/oldString/newString/g' {} +
@Cristian You are welcome! However, the find-based solution you've posted in your question should also work. Probably you simple had a typo somewhere.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.