-1

I am trying to recursively find and replace all instances of root with usr/local.

I know that this command:

find ./ -type f -exec sed -i -e 's/apple/orange/g' {} \;

works when trying to replace a string without "/" with another, but how do I do this to include "/" in the replaced string?

melpomene
  • 84,125
  • 8
  • 85
  • 148
quantMath
  • 1
  • 3
  • escape that thing: `'s/root/user\/local/g'` – JNevill Sep 19 '17 at 19:36
  • @JNevill when i tried this i get: sed: RE error: illegal byte sequence – quantMath Sep 19 '17 at 19:37
  • Are you on a [mac](https://stackoverflow.com/questions/19242275/re-error-illegal-byte-sequence-on-mac-os-x)? – JNevill Sep 19 '17 at 19:39
  • Yes. I am on a mac @JNevill – quantMath Sep 19 '17 at 19:40
  • Then it may be a locale type of issue. Try: `find ./ -type f -exec LC_ALL=C sed -i -e 's/root/user\/local/g' {} \;` – JNevill Sep 19 '17 at 19:42
  • This gives me find: LC_ALL=C: No such file or directory @JNevill – quantMath Sep 19 '17 at 19:43
  • Fine then. Stick that thing before the `find` if it's going to be picky like that: `LC_ALL=C find ./ -type f -exec sed -i -e 's/root/user\/local/g' {} \;` Not 100% if that will work, but it's worth a shot. – JNevill Sep 19 '17 at 19:46
  • This works, but gives me 2 versions of the file, one with a -e after it (with the previous changes), and one without -e which has the updated version. How do I make the -e version removed? @JNevill thank you for your help sorry for the silly questions – quantMath Sep 19 '17 at 19:52
  • Honestly... I have no idea on that one. Perhaps drop that oddball `-e` flag on your sed command. Total 100% guess on that one though. – JNevill Sep 19 '17 at 19:54

1 Answers1

0

In order to use a / in the replacement it can either be escaped with a \,
or the s command can use a different delimiter:

sed 's|root|usr/local|g' ...

Additionally the (non-standard) -i option requires an argument in FreeBSD sed(1) and, by extension, macOS (OS X) sed(1). In this case giving a zero-length argument (-i '') will have the same effect as having no argument would for GNU sed(1).

However the man-page warns against that usage:

It is not recommended to give a zero-length extension when in-place editing files, as you risk corruption or partial content in situations where disk space is exhausted, etc.

Also, if the extention is not in its own argument then the syntaxes are compatible:

sed -i.bak 's|root|usr/local|g' ...
kdhp
  • 2,096
  • 14
  • 15