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

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 another approaches .
  • 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:

javascript code
sed -i -- 's/foo/bar/g' * 
perl -i -pe 's/foo/bar/g' ./*
[ad type=”banner”]

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

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

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

If you are using zsh:

javascript code
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):

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

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

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:

javascript code
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

javascript code
find . -type f -name "*baz*" -exec sed -i 's/foo/bar/g' {} +
javascript code
( shopt -s globstar dotglob 
sed -i -- 's/foo/bar/g' **baz*
sed -i -- 's/foo/bar/g' **.baz
)
[ad type=”banner”]

If you are using zsh:

javascript code
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):

javascript code
f ind . -type f -executable -exec sed -i 's/foo/bar/g' {} +
zsh:
sed -i -- 's/foo/bar/g' **/*(D*)

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:

javascript code
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,

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

javascript code
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

 

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

Another solution using perl:

 

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

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 :):

         

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

Replace foo with bar only on the 4th line:

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

Multiple replace operations: replace with different strings

You can combine sed commands:

javascript code
sed -i 's/foo/bar/g; s/baz/zab/g; s/Alice/Joan/g' file
[ad type=”banner”]

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

Perl commands:

javascript code
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:

javascript code
#! /usr/bin/sed -f 
s/foo/bar/g
s/baz/zab/g

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):

javascript code
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 :

javascript code
                  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.
  •  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:
javascript code
SOME_PIPELINE |
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:
javascript code
                       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:
javascript code
sed 's/[]$&^*\./[]/\\&/g
s| *\([^ ]*\) *\([^ ]*\).*|s/\1/\2/g|
' <patterns.txt |
sed -f- ./editfile >outfile

Multiple replace operations: replace multiple patterns with the same string

Replace any of foo, bar or baz with foobar

javascript code
sed -Ei 's/foo|bar|baz/foobar/g' file

or  using perl

javascript code
perl -i -pe 's/foo|bar|baz/foobar/g' file

  • If you have list of files you can use,
javascript code
replace "old_string" "new_string" -- file_name1 file_name2 file_name3 

Categorized in: