3

I run the following command to find and replace an old web address to a new one.

find . -type f -print0 | xargs -0 sed -i \
's/http:\/\/www\.oldwebaddress\.com\/techblog/https:\/\/github\.com\/myname/g'

However I get the following error.

sed: 1: "./.DS_Store": invalid command code .

I tried this one after reading some of Stack Overflow posts but didn't work either.

find . -type f -print0 | xargs -0 sed -i "" \
's/http:\/\/www\.oldwebaddress\.com\/techblog/https:\/\/github\.com\/myname/g'

sed: RE error: illegal byte sequence

What am I doing wrong here?

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
shin
  • 31,901
  • 69
  • 184
  • 271

2 Answers2

6

The sed on Mac OS X accepts the -i option but requires an argument, the suffix to use for the backup files. It is not optional as it is with GNU sed. So, the sed script tries to use your s/// command as the suffix, and then the first file name didn't happen to be a valid sed command.

For the second attempt, with -i "", it is not quite so clear what's up. I assume there's either a backslash after the "" or the whole lot is really on one line, so that it is syntactically correct.

It is simpler to use some character other than / as the separator when editing path names. Often, % works:

-e 's%http://www\.oldwebaddress\.com/techblog%https://github\.com/myname%g'

but you can use any character; Control-A or Control-G are quite effective too and even more unlikely to appear in a URL than %.

It is not clear to me, though, why you're getting the RE error (invalid byte sequence). Copying and pasting from the question doesn't show a problem, and the other question referenced suggests LANG=C LC_CTYPE=C but I'm not running into problems with LANG=en_US.UTF-8 and nothing set for LC_CTYPE.

Community
  • 1
  • 1
Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
1

Does this help?

Also if you will just do -print instead of -print0 then you can replace xargs -0 with just xargs.

You might also consider using perl instead of BSD sed.

find . -type f -print | xargs perl -pi.bak -e 's/http\:\/\/www\.oldwebaddress\.com\/techblog/https\:\/\/github\.com\/myname/g'

Above should do the replacements and save all files backups adding .bak at the end of filenames. Use perl -pi -e if you don't want backups to be created.

Community
  • 1
  • 1
Michal Gasek
  • 6,173
  • 1
  • 18
  • 20