Replace String in Files/File
1. Replacing all occurrences of one string with another in all files in the current directory:
These are for cases where you 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 ”.
· Non recursive, files in this directory only:
· Recursive, regular files (including hidden ones) in this and all subdirectories
If you are using zsh:
(may fail if the list is too big, see zargs to work around).
If you are using bash, bash having no support for glob qualifiers, you can’t check for regular files:
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:
· Recursive, regular files in this and all subdirectories
If you are using bash:
If you are using zsh:
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):
3. Replace only if the string is found in a certain context
· Replace foo with bar only there is a baz later on the same line:
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 . We need to repeat the operation for all foo occurrences, which is done with the t conditional branching.
· Replace foo with bar only if foo is found on the 3d column (field) of the input file (assuming whitespace-separated fields):
(need 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:
Another solution using perl:
NOTE: both the awk and perl solutions will print space separated fields even if the input file had tabs. For a different field use $F[N-1] where N is the field umber you want and for a different field separator use (the $”=”:” sets the output field separator to :):
· Replace foo with bar only on the 4th line:
4. Multiple replace operations: replace with different strings
You can combine sed commands:
or Perl commands
If you have a large number of patterns, it is easier to save your patterns and their replacements in a sed script file:
Or, if you have too many patterns pairs for the above to be feasible, you can read pattern pairs from a file (two space separated patterns, $pattern and $replacement, per line):
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:
Then, run the sed script on your input file(s):
5. Multiple replace operations: replace multiple patterns with the same string
Replace any of foo, bar or baz with foobar