Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

Replacing strings in files based on certain search criteria is a very common task. How can I

  • replace string foo with bar in all files in the current directory?
  • do the same recursively for sub directories?
  • replace only if the file name matches another string?
  • replace only if the string is found in a certain context?
  • replace if the string is on a certain line number?
  • replace multiple strings with the same replacement
  • replace multiple strings with different replacements
share|improve this question
This is intended to be a canonical Q&A on this subject (see this meta discussion), please feel free to edit my answer below or add your own. – terdon Feb 1 '14 at 17:08
I just want to replace foo with bar in a specific line. all the lines contains foo's.what to do? – user2433165 Sep 4 '14 at 11:38
@user2433165 look at the last bullet point of solution number 3 in my answer below. Just change 4 to the line number you want. – terdon Sep 4 '14 at 14:05
@mikeserv I don't see why not. My answer is basically sed, awk and perl all of which are available on the vast majority of systems. Note that it's a community wiki answer and is so precisely to encourage people to edit and improve it. If you have more portable solutions, please add them. – terdon Sep 4 '14 at 18:23
@mikeserv cool. Please post an answer, or edit mine, giving alternate solutions then. That's the point of the canonical Q&As. Not that there necessarily be a single all inclusive answer, but that it be a single all inclusive thread. Oh, and -i is not GNU, it is also BSD and maybe more. It's just not POSIX. – terdon Sep 4 '14 at 18:54
up vote 379 down vote accepted

1. Replacing all occurrences of one string with another in all files in the current directory:

These are for cases where you know that the directory contains only regular files and that you want to process all non-hidden files. If that is not the case, use the approaches in 2.

All sed solutions in this answer assume GNU sed. If using FreeBSD or OS/X, replace -i with -i ''. Also note that the use of the -i switch with any version of sed has certain filesystem security implications and is inadvisable in any script which you plan to distribute in any way.

  • Non recursive, files in this directory only:

    sed -i -- 's/foo/bar/g' *
    perl -i -pe 's/foo/bar/g' ./* 

    (the perl one will fail for file names ending in | or space)).

  • Recursive, regular files (including hidden ones) in this and all subdirectories

    find . -type f -exec sed -i 's/foo/bar/g' {} +

    If you are using zsh:

    sed -i -- 's/foo/bar/g' **/*(D.)

    (may fail if the list is too big, see zargs to work around).

    Bash can't check directly for regular files, a loop is needed (braces avoid setting the options globally):

    ( shopt -s globstar dotglob;
        for file in **; do
            if [[ -f $file ]] && [[ -w $file ]]; then
                sed -i -- 's/foo/bar/g' "$file"

    The files are selected when they are actual files (-f) and they are writable (-w).

2. Replace only if the file name matches another string / has a specific extension / is of a certain type etc:

  • Non-recursive, files in this directory only:

    sed -i -- 's/foo/bar/g' *baz*    ## all files whose name contains baz
    sed -i -- 's/foo/bar/g' *.baz    ## files ending in .baz
  • Recursive, regular files in this and all subdirectories

    find . -type f -name "*baz*" -exec sed -i 's/foo/bar/g' {} +

    If you are using bash (braces avoid setting the options globally):

    ( shopt -s globstar dotglob
        sed -i -- 's/foo/bar/g' **baz*
        sed -i -- 's/foo/bar/g' **.baz

    If you are using zsh:

    sed -i -- 's/foo/bar/g' **/*baz*(D.)
    sed -i -- 's/foo/bar/g' **/*.baz(D.)

    The -- serves to tell sed that no more flags will be given in the command line. This is useful to protect against file names starting with -.

  • If a file is of a certain type, for example, executable (see man find for more options):

    find . -type f -executable -exec sed -i 's/foo/bar/g' {} +


    sed -i -- 's/foo/bar/g' **/*(D*)

3. Replace only if the string is found in a certain context

  • Replace foo with bar only if there is a baz later on the same line:

    sed -i 's/foo\(.*baz\)/bar\1/' file

    In sed, using \( \) saves whatever is in the parentheses and you can then access it with \1. There are many variations of this theme, to learn more about such regular expressions, see here.

  • Replace foo with bar only if foo is found on the 3d column (field) of the input file (assuming whitespace-separated fields):

    gawk -i inplace '{gsub(/foo/,"baz",$3); print}' file

    (needs gawk 4.1.0 or newer).

  • For a different field just use $N where N is the number of the field of interest. For a different field separator (: in this example) use:

    gawk -i inplace -F':' '{gsub(/foo/,"baz",$3);print}' file

    Another solution using perl:

    perl -i -ane '$F[2]=~s/foo/baz/g; $" = " "; print "@F\n"' foo 

    NOTE: both the awk and perl solutions will affect spacing in the file (remove the leading and trailing blanks, and convert sequences of blanks to one space character in those lines that match). For a different field, use $F[N-1] where N is the field number you want and for a different field separator use (the $"=":" sets the output field separator to :):

    perl -i -F':' -ane '$F[2]=~s/foo/baz/g; $"=":";print "@F"' foo 
  • Replace foo with bar only on the 4th line:

    sed -i '4s/foo/bar/g' file
    gawk -i inplace 'NR==4{gsub(/foo/,"baz")};1' file
    perl -i -pe 's/foo/bar/g if $.==4' file

4. Multiple replace operations: replace with different strings

  • You can combine sed commands:

    sed -i 's/foo/bar/g; s/baz/zab/g; s/Alice/Joan/g' file

    Be aware that order matters (sed 's/foo/bar/g; s/bar/baz/g' will substitute foo with baz).

  • or Perl commands

    perl -i -pe 's/foo/bar/g; s/baz/zab/g; s/Alice/Joan/g' file
  • If you have a large number of patterns, it is easier to save your patterns and their replacements in a sed script file:

    #! /usr/bin/sed -f
  • Or, if you have too many pattern pairs for the above to be feasible, you can read pattern pairs from a file (two space separated patterns, $pattern and $replacement, per line):

    while read -r pattern replacement; do   
        sed -i "s/$pattern/$replacement/" file
    done < patterns.txt
  • That will be quite slow for long lists of patterns and large data files so you might want to read the patterns and create a sed script from them instead. The following assumes a <space> delimiter separates a list of MATCH<space>REPLACE pairs occurring one-per-line in the file patterns.txt :

    sed 's| *\([^ ]*\) *\([^ ]*\).*|s/\1/\2/g|' <patterns.txt |
    sed -f- ./editfile >outfile

    The above format is largely arbitrary and, for example, doesn't allow for a <space> in either of MATCH or REPLACE. The method is very general though: basically, if you can create an output stream which looks like a sed script, then you can source that stream as a sed script by specifying sed's script file as -stdin.

  • You can combine and concatenate multiple scripts in similar fashion:

    sed -e'#some expression script'  \
        -f./script_file -f-          \
        -e'#more inline expressions' \
    ./actual_edit_file >./outfile

    A POSIX sed will concatenate all scripts into one in the order they appear on the command-line. None of these need end in a \newline.

  • grep can work the same way:

    sed -e'#generate a pattern list' <in |
    grep -f- ./grepped_file
  • When working with fixed-strings as patterns, it is good practice to escape regular expression metacharacters. You can do this rather easily:

    sed 's/[]$&^*\./[]/\\&/g
         s| *\([^ ]*\) *\([^ ]*\).*|s/\1/\2/g|
    ' <patterns.txt |
    sed -f- ./editfile >outfile

5. Multiple replace operations: replace multiple patterns with the same string

  • Replace any of foo, bar or baz with foobar

    sed -Ei 's/foo|bar|baz/foobar/g' file
  • or

    perl -i -pe 's/foo|bar|baz/foobar/g' file
share|improve this answer
@StéphaneChazelas thanks for the edit, it did indeed fix several things. However, please don't remove information that is relevant to bash. Not everyone uses zsh. By all means add zsh info but there is no reason to remove the bash stuff. Also, I know that using the shell for text processing is not ideal but there are cases where it is needed. I edited in a better version of my original script that will create a sed script instead of actually using the shell loop to parse. This can be useful if you have several hundred pairs of patterns for example. – terdon Jan 16 '15 at 15:10
@terdon, your bash one is incorrect. bash before 4.3 will follow symlinks when descending. Also bash has no equivalent for the (.) globbing qualifier so can't be used here. (you're missing some -- as well). The for loop is incorrect (missing -r) and means making several passes in the files and adds no benefit over a sed script. – Stéphane Chazelas Jan 16 '15 at 15:16
@StéphaneChazelas I don't see why following symlinks is a problem here. If the links are in the directory in most cases I would want to follow them. I'm afraid I don't understand what you mean about the (.) which is, I guess, some zsh magic I am unfamiliar with. I fixed the shell loop (and added a few -- though not in all examples), its point is in dealing with hundreds of patterns and will only read the pattern file once. It produces a sed script. – terdon Jan 16 '15 at 15:53
@terdon What does -- after sed -i and before the substitute command indicate? – Geek Sep 28 '15 at 11:29
@Geek that's a feature of many commands. It signifies the end of options and lets you pass arguments starting with -. Using it ensures that the commands will work on files with names like -foo. Without it, the -f would be parsed as an option. – terdon Sep 28 '15 at 11:42

A good replacement Linux tool is rpl, that was originally written for the Debian project, so it is available with apt-get install rpl in any Debian derived distro, and may be for others, but otherwise you can download the tar.gz file in SourgeForge.

Simplest example of use:

 $ rpl old_string new_string test.txt

Note that if the string contain spaces it should be enclosed in quotation marks. By default rpl take care of capital letters but not of complete words, but you can change these defaults with options -i (ignore case) and -w (whole words). You can also specify multiple files:

 $ rpl -i -w "old string" "new string" test.txt test2.txt

Or even specify the extensions (-x) to search or even search recursively (-R) in the directory:

 $ rpl -x .html -x .txt -R old_string new_string test*

You can also search/replace in interactive mode with -p (prompt) option:

The output show the numbers of files/string replaced and the type of search (case in/sensitive, whole/partial words), but it can be silent with the -q (quiet mode) option, or even more verbose, listing line numbers that contain matches of each file and directory with -v (verbose mode) option.

Other options that are worth remembering are -e (honor escapes) that allow regular expressions, so you can search also tabs (\t), new lines (\n),etc. Even you can use -f to force permissions (of course, only when the user have write permissions) and -d to preserve the modification times`).

Finally, if you are unsure of which will make exactly, use the -s (simulate mode).

share|improve this answer

How to do a search and replace over multiple files suggests:

You could also use find and sed, but I find that this little line of perl works nicely.

perl -pi -w -e 's/search/replace/g;' *.php
  • -e means execute the following line of code.
  • -i means edit in-place
  • -w write warnings
  • -p loop over the input file, printing each line after the script is applied to it.

My best results come from using perl and grep (to ensure that file have the search expression )

perl -pi -w -e 's/search/replace/g;' $( grep -rl 'search' )
share|improve this answer

From a user's perspective, a nice & simple Unix tool that does the job perfectly is qsubst. For example,

% qsubst foo bar *.c *.h

will replace foo with bar in all my C files. A nice feature is that qsubst will do a query-replace, i.e., it will show me each occurrence of foo and ask whether I want to replace it or not. [You can replace unconditionally (no asking) with -go option, and there are other options, e.g., -w if you only want to replace foo when it is a whole word.]

How to get it: qsubst was invented by der Mouse (from McGill) and posted to comp.unix.sources 11(7) in Aug. 1987. Updated versions exist. For example, the NetBSD version qsubst.c,v 1.8 2004/11/01 compiles and runs perfectly on my mac.

share|improve this answer

You can use Vim in Ex mode:

replace string ALF with BRA in all files in the current directory?

for CHA in *
  ex -sc '%s/ALF/BRA/g' -cx "$CHA"

do the same recursively for sub directories?

find -type f -exec ex -sc '%s/ALF/BRA/g' -cx {} ';'

replace only if the file name matches another string?

for CHA in *.txt
  ex -sc '%s/ALF/BRA/g' -cx "$CHA"

replace only if the string is found in a certain context?

ex -sc 'g/DEL/s/ALF/BRA/g' -cx file

replace if the string is on a certain line number?

ex -sc '2s/ALF/BRA/g' -cx file

replace multiple strings with the same replacement

ex -sc '%s/\vALF|ECH/BRA/g' -cx file

replace multiple strings with different replacements

ex -sc '%s/ALF/BRA/g|%s/FOX/GOL/g' -cx file
share|improve this answer

I used this:

grep -r "old_string" -l | tr '\n' ' ' | xargs sed -i 's/old_string/new_string/g'
  1. List all files that contain old_string.

  2. Replace newline in result with spaces (so that the list of files can be fed to sed.

  3. Run sed on those files to replace old string with new.

Update: The above result will fail on filenames that contain whitespaces. Instead, use:

grep --null -lr "old_string" | xargs --null sed -i 's/old_string/new_string/g'

share|improve this answer
Note that this will fail if any of your file names contain spaces, tabs or newlines. Use grep --null -lr "old_string" | xargs --null sed -i 's/old_string/new_string/g' will make it deal with arbitrary file names. – terdon Oct 26 '15 at 17:07
thanks guys. added update and left the old code cause it's an interesting caveat that could be useful to someone unaware of this behavior. – o_o_o-- Oct 26 '15 at 20:59

protected by Community Jul 27 '15 at 21:05

Thank you for your interest in this question. Because it has attracted low-quality or spam answers that had to be removed, posting an answer now requires 10 reputation on this site (the association bonus does not count).

Would you like to answer one of these unanswered questions instead?

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