180

In the linux shell, the following command will recursively search and replace all instances of 'this' with 'that' (I don't have a Linux shell in front of me, but it should do).

find . -name "*.txt" -print | xargs sed -i 's/this/that/g'

What will a similar command on OSX look like?

1
  • 1
    Should probably moved to apple.stackexchange.com as it's not generic enough for linux nor all devs. Commented Jul 14, 2016 at 5:42

14 Answers 14

308

OS X uses a mix of BSD and GNU tools, so best always check the documentation (although I had it that less didn't even conform to the OS X manpage):

https://web.archive.org/web/20170808213955/https://developer.apple.com/legacy/library/documentation/Darwin/Reference/ManPages/man1/sed.1.html

sed takes the argument after -i as the extension for backups. Provide an empty string (-i '') for no backups.

The following should do:

find . -type f -name '*.txt' -exec sed -i '' s/this/that/g {} +

The -type f is just good practice; sed will complain if you give it a directory or so.

-exec is preferred over xargs; you needn't bother with -print0 or anything.

The {} + at the end means that find will append all results as arguments to one instance of the called command, instead of re-running it for each result. (One exception is when the maximal number of command-line arguments allowed by the OS is breached; in that case find will run more than one instance.)

If you get an error like "invalid byte sequence," it might help to force the standard locale by adding LC_ALL=C at the start of the command, like so:

LC_ALL=C find . -type f -name '*.txt' -exec sed -i '' s/this/that/g {} +

22
  • 3
    My "this" in this substitution contains a forward slash (localhost/site) -- I am substituting parts of a URL in an .html file....how do I make such a substitution. I tried putting in double-quotes, but it fails.
    – Satchel
    Commented Sep 18, 2013 at 4:00
  • 9
    Sed syntax allows using almost any character in place of the slash, e.g. you could use the % character: sed "s%localhost/site%blah/blah%". Another alternative is to backslash-escape the separator: sed "s/localhost\/site/blah\/blah/". Commented Sep 18, 2013 at 11:06
  • Thank you let me try that. I did however try using {} to separate the slash and I still got an error...
    – Satchel
    Commented Sep 19, 2013 at 2:39
  • 22
    Anybody else getting illegal byte sequence error? if so, try: LC_ALL=C find . -type f -name '*.txt' -exec sed -i '' s/this/that/ {} +, it worked for me.
    – Caio Mar
    Commented May 31, 2016 at 14:10
  • 15
    This will be replacing only one ocurreny per file, use /g for multiple ocurrencies like LC_ALL=C find . -type f -exec sed -i '' s/search/replace/g {} +
    – jamesjara
    Commented Aug 22, 2017 at 6:20
243

For the mac, a more similar approach would be this:

find . -name '*.txt' -print0 | xargs -0 sed -i "" "s/form/forms/g"
6
  • 24
    I wish I could upvote this every time I come back to it and use it. It'd be at +15 by now, easy.
    – yurisich
    Commented Feb 26, 2015 at 15:35
  • 1
    For some reason, it does not work for me. It does nothing. I'm inside the folder form360 and I´m trying to change all string instances with the name easyform to form360, I´m running the following command: find . -name '*.php' -print0 | xargs -0 sed -i "" "s/easyform/form360/g" Commented Jan 26, 2017 at 21:23
  • 2
    for me, this should be correct answer. It's the only one that worked for me. Commented Feb 1, 2017 at 6:08
  • 1
    -print0 | xargs -0 does not work on my mac when file name contains space.
    – acerphenix
    Commented Apr 29, 2017 at 10:49
  • 1
    sed: .: in-place editing only works for regular files Commented Aug 2, 2017 at 15:38
26

As an alternative solution, I'm using this one on Mac OSX 10.7.5

grep -ilr 'old-word' * | xargs -I@ sed -i '' 's/old-word/new-word/g' @

Credit goes to: Todd Cesere's answer

4
  • 3
    This one works well! Other scripts adds an extra end of line in some cases on OSX! Thanks a lot! Commented Dec 6, 2019 at 21:14
  • Downside of using grep with * is that it will be much more slower. Consider -I to avoid binary files, use --exclude-dir or a pattern like {dir1,dir2}
    – zevarito
    Commented Nov 16, 2020 at 20:18
  • 1
    does NOT work $ grep -ilr 'fastapi' * | xargs -I@ sed -i '' 's/fastapi/flask/g' @ and output is sed: RE error: illegal byte sequence sed: RE error: illegal byte sequence sed: RE error: illegal byte sequence sed: RE error: illegal byte sequence sed: RE error: illegal byte sequence sed: RE error: illegal byte sequence sed: RE error: illegal byte sequence
    – uberrebu
    Commented Apr 17, 2021 at 4:39
  • 1
    @uberrebu It worked, but you are including a parameter to remove a trailing newline and one or all of your directories include binary files. Fortunately for you, sed fails, instead of corrupting the files. Large-scale destructive commands are best run in folders with some method of version control (ie. git) to prevent irreversible damage. Commented Oct 29, 2022 at 11:42
19

None of the above work on OSX.

Do the following:

perl -pi -w -e 's/SEARCH_FOR/REPLACE_WITH/g;' *.txt
7
  • 1
    how to scape '/' if SEARCH_FOR and REPLACE_WITH are paths?
    – rraallvv
    Commented Mar 29, 2013 at 16:35
  • Use a different delimiter. If you're using paths, a colon or pipe would work. 's|SEARCH|REPLACE|g', for example. Our use braces, as in 's{SEARCH}{REPLACE}'.
    – dannysauer
    Commented Sep 6, 2013 at 1:04
  • 1
    dito question, trying it no on Mac -- but it seems to generate an error? For example, my path gets interpreted as a file? -bash: localhost/nohost: No such file or directory
    – Satchel
    Commented Sep 18, 2013 at 4:02
  • this does not recurse through folders deep. Only one level. Commented Nov 27, 2013 at 14:05
  • For more info about this command read this lifehacker.com/5810026/…
    – kuzdu
    Commented Sep 26, 2018 at 14:41
14

If you are using a zsh terminal you're able to use wildcard magic:

sed -i "" "s/search/high-replace/g" *.txt

2
  • 2
    As OSX now has ZSH terminals by default, this should be the accepted answer. Commented Jan 27, 2022 at 11:15
  • Tried all the above answers but none worked, except this one, on Macbook Air M1 2021. Thank you! Commented Apr 26, 2022 at 15:38
8

A version that works on both Linux and Mac OS X (by adding the -e switch to sed):

export LC_CTYPE=C LANG=C
find . -name '*.txt' -print0 | xargs -0 sed -i -e 's/this/that/g'
4
  • I had to do the export from this answer + the line from the accepted answer (I didn't want backup files to be generated)
    – Lance
    Commented Apr 29, 2014 at 19:46
  • 2
    to adress the 'illegal byte sequence' error, try setting the LOCALE before running the command: export LC_CTYPE=C && export LANG=C
    – cjoy
    Commented Jan 6, 2016 at 1:24
  • 1
    DO NOT EVER RUN this with '*' instead of '*.filetype' as I did if you are using Git. Or you can say goodbye to all your unpublished work.
    – Sergey
    Commented May 26, 2016 at 9:11
  • 1
    The mac version of the sed command requires an '' after the -i, so this answer is incorrect
    – G Hx
    Commented Jul 25, 2018 at 22:08
6

This is my workable one. on mac OS X 10.10.4

grep -e 'this' -rl . | xargs sed -i '' 's/this/that/g'

The above ones use find will change the files that do not contain the search text (add a new line at the file end), which is verbose.

1
  • does NOT work $ grep -e 'fastapi' -rl . | xargs sed -i '' 's/fastapi/flask/g' and here is output sed: RE error: illegal byte sequence
    – uberrebu
    Commented Apr 17, 2021 at 4:47
6

2021

What worked for me :

LC_ALL=C && LANG=C && find . -type f | xargs sed -i '' 's/old/new/g'
2
  • It worked for me without the LC_ALL=C && LANG=C && part. Why do you need that? Commented Aug 23, 2021 at 2:54
  • You'll get a byte sequence error about ASCII to UTF conversion otherwise (likely depending on what characters you're using)
    – t56k
    Commented Sep 19, 2023 at 2:36
3

Whenever I type this command I always seem to hose it up, or forget a flag. I created a Gist on github based off of TaylanUB's answer that does a global find replace from the current directory. This is Mac OSX specific.

https://gist.github.com/nateflink/9056302

It's nice because now I just pop open a terminal then copy in:

curl -s https://gist.github.com/nateflink/9056302/raw/findreplaceosx.sh | bash -s "find-a-url.com" "replace-a-url.com"

You can get some weird byte sequence errors, so here is the full code:

#!/bin/bash
#By Nate Flink

#Invoke on the terminal like this
#curl -s https://gist.github.com/nateflink/9056302/raw/findreplaceosx.sh | bash -s "find-a-url.com" "replace-a-url.com"

if [ -z "$1" ] || [ -z "$2" ]; then
  echo "Usage: ./$0 [find string] [replace string]"
  exit 1
fi

FIND=$1
REPLACE=$2

#needed for byte sequence error in ascii to utf conversion on OSX
export LC_CTYPE=C;
export LANG=C;

#sed -i "" is needed by the osx version of sed (instead of sed -i)
find . -type f -exec sed -i "" "s|${FIND}|${REPLACE}|g" {} +
exit 0
1

I used this format - but...I found I had to run it three or more times to get it to actually change every instance which I found extremely strange. Running it once would change some in each file but not all. Running exactly the same string two-four times would catch all instances.

find . -type f -name '*.txt' -exec sed -i '' s/thistext/newtext/ {} +
1
  • 2
    You needed to run this command multiple times b/c your sed regex needs a g at the end, otherwise it only replaces the first occurrence of thistext in a line. So your regex should be s/thistext/newtext/g Commented May 11, 2020 at 14:51
1

this worked for me on mac

LC_ALL=C && LANG=C && find . -type f | xargs sed -i '' 's/OLD_STRING/NEW_STRING/g'

however it was much faster with specifying the file types I needed to search/replace in

LC_ALL=C && LANG=C && find . -type f -name '*.html' | xargs sed -i '' 's/OLD_STRING/NEW_STRING/g'

and as I was search/replacing urls, had to put backslash (\) before slashes

LC_ALL=C && LANG=C && find . -type f -name '*.html' | xargs sed -i '' 's/https:\/\/yahoo.com/https:\/\/google.com/g'
0
find . -type f | xargs sed -i '' 's/string1/string2/g'

Refer here for more info.

0

For both macOS and Linux:

I'm not sure that the other answers address both Linux and macOS. If there are some that do, perhaps we can edit them to make that point clear.

Below is what I used in order to target both platforms.

Assume the file we want to perform the find/replace on contains the following text:

file.txt:

{{FROM}} hello world

Here is the script, replace.bash:

    #!/bin/bash
    PATTERN="s/{{FROM}}/HELLOWORLD/"
    if [[ `uname -s`" == "Darwin" ]]; then
        sed -i '' "$PATTERN" file.txt
        echo Darwin
    else
        sed -i "$PATTERN" file.txt
        echo Linuxxxx
    fi

I later discovered that using single brackets and a single equals cooperated better between sh and bash:

replace.sh:

    PATTERN="s/{{FROM}}/HELLOWORLD/"
    if [ `uname -s` = "Darwin" ]; then
        sed -i '' "$PATTERN" file.txt
        echo Darwin
    else
        sed -i "$PATTERN" file.txt
        echo Linuxxxx
    fi

Your own cross-platform sed:

I can see how someone might replace $PATTERN with $1 and file.txt with $2 and actually be able to create a wrapper around sed that works on both platforms, such as:

ssed:

    PATTERN="$1"
    FILE=$2
    if [ `uname -s` = "Darwin" ]; then
        sed -i '' "$PATTERN" $FILE
    else
        sed -i "$PATTERN" $FILE
    fi
$ chmod 755 ssed
$ ./ssed 's/{{FROM}}/jameswashere/' file

The file would then contain:

jameswashere hello world

What about recursive find/replace?

Now that we have our own platform-independent sed wrapper, we can use it, along with find, to loop through subdirectories and perform the find/replace on matching files:

$ find . -name "file" -exec ./ssed 's/{{FROM}}/that/g' {} \;
-1

https://bitbucket.org/masonicboom/serp is a go utility (i.e. cross-platform), tested on OSX, that does recursive search-and-replace for text in files within a given directory, and confirms each replacement. It's new, so might be buggy.

Usage looks like:

$ ls test
a  d  d2 z
$ cat test/z
hi
$ ./serp --root test --search hi --replace bye --pattern "*"                         
test/z: replace hi with bye? (y/[n]) y
$ cat test/z
bye

Not the answer you're looking for? Browse other questions tagged or ask your own question.