Skip to content

Instantly share code, notes, and snippets.

@startergo
Last active September 1, 2023 21:21
Show Gist options
  • Save startergo/d9502d4c6d3cc05629e8f180fc02248f to your computer and use it in GitHub Desktop.
Save startergo/d9502d4c6d3cc05629e8f180fc02248f to your computer and use it in GitHub Desktop.
Sed find and replace in macOS
  • Example 1:
find . -name "*.py" -exec sed -i '' -e 's|#!/usr/bin/python|/#!usr/bin/env python|g' {} \;
  • Example 2:
find . -type f -exec sed -i '' -e 's|#!/usr/bin/python|/#!usr/bin/env python|g' {} \;

If you get RE error: illegal byte sequence on Mac OS X add these lines:

export LC_CTYPE=C 
export LANG=C

To ~/.bash_profile or ~/.zshrc file(s) (whichever you use)

  • Setting LC_CTYPE to C causes each byte in strings to be its own character without applying any encoding rules. Since a violation of (UTF-8) encoding rules causes the original problem, this makes the problem go away. However, the price you pay is that the shell and utilities then only recognize the basic English letters (the ones in the 7-bit ASCII range) as letters.

  • If you don't want to modify the ASCII range use perl instead:

find . -type f -print0 | xargs -0 perl -pi -e 's|#!/usr/bin/python|/#!usr/bin/env python|g' {} \;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment