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.

Community
  • 1
  • 1
Cristian
  • 1,590
  • 5
  • 23
  • 38
  • both solutions seem fine to me. Isn't it working at all or to what extend? – fedorqui Jul 17 '15 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? – Cristian Jul 17 '15 at 12:55

1 Answers1

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.

hek2mgl
  • 152,036
  • 28
  • 249
  • 266