3

I have a large set of files in which I need to replace a full URL scheme. Some filenames contain spaces. After much searching and rial and error, this is the closest I've come:

find /somedir -type f -print0 -exec sed -i'' -e 's#http\\:\\/\\/domain.com#https\\:\\/\\/www.domain.com#g' {} +

The resulting file has the scheme http: removed, leaving the // - i.e. '//www.domain.com'

Additionally, a NEW file is created, appending -e to the filename. - i.e. some file.php-e which obviously unwanted.

While this would certainly suffice (after removing the *-e files, the OCD in me really wants to know how to do this correctly. Note: I'm working locally on a Mac but will also be performing this on linux.

Any ideas are greatly appreciated!

2

Solution 1: One way is to use find with xargs:

find /dir -type f -print0 | xargs -0 sed -i 's#http://domain.com#https://www.domain.com#g'

Solution 2: Another one would be to use find with -exec, very similar as in your question:

find /dir -type f -exec sed -i 's#http://domain.com#https://www.domain.com#g' {} +

Both solutions will call sed with mutiple files as arguments. So sed is not called once for every file, but for every set of files.

Solution 3: Instead of sed, you could also use perl for the search-replace-job:

perl -i -pe 's#http://domain.com#https://www.domain.com#g' file

Combined with the find/xargs command:

find /dir -type f -print0 | xargs -0 perl -i -pe 's#http://domain.com#https://www.domain.com#g'
  • unfortunately the first two error with: command c expects \ followed by text. The last one works on a specific file but how do I do it recursively (keeping in mind possible spaces in filenames/dirs)? – Chris Chapman Jul 21 '15 at 16:41
  • @ChrisChapman Just combine it with the find/xargs command: find /dir -type f -print0 | xargs -0 perl -i -pe 's#http://domain.com#https://www.domain.com#g' – chaos Jul 21 '15 at 17:30
  • Ding Ding Ding! - we have a winner! Thanks a ton. Perl was a jillion times faster too. – Chris Chapman Jul 21 '15 at 17:43

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.