I need to replace a string in a lot of files in a folder, with only ssh
access to the server. How can I do this?
问题:
回答1:
cd /path/to/your/folder
sed -i 's/foo/bar/g' *
Occurrences of "foo" will be replaced with "bar".
回答2:
Similar to Kaspar's answer but with the g flag to replace all the occurrences on a line.
find ./ -type f -exec sed -i 's/string1/string2/g' {} \;
For global case insensitive:
find ./ -type f -exec sed -i 's/string1/string2/gI' {} \;
回答3:
@kev's answer is good, but only affects files in the immediate directory.The example below uses grep to recursively find files. It works for me everytime.
grep -rli 'old-word' * | xargs -i@ sed -i 's/old-word/new-word/g' @
回答4:
This worked for me:
find ./ -type f -exec sed -i 's/string1/string2/' {} \;
Howerver, this did not: sed -i 's/string1/string2/g' *
. Maybe "foo" was not meant to be string1 and "bar" not string2.
回答5:
There are a few standard answers to this already listed. Generally, you can use find to recursively list the files and then do the operations with sed or perl.
For most quick uses, you may find the command rpl is much easier to remember. Here is replacement (foo -> bar), recursively on all files:
rpl -R foo bar .
You'll probably need to install it (apt-get install rpl
or similar).
However, for tougher jobs that involve regular expressions and back substitution, or file renames as well as search-and-replace, the most general and powerful tool I'm aware of is repren, a small Python script I wrote a while back for some thornier renaming and refactoring tasks. The reasons you might prefer it are:
- Support renaming of files as well as search-and-replace on file contents.
- See changes before you commit to performing the search and replace.
- Support regular expressions with back substitution, whole words, case insensitive, and case preserving (replace foo -> bar, Foo -> Bar, FOO -> BAR) modes.
- Works with multiple replacements, including swaps (foo -> bar and bar -> foo) or sets of non-unique replacements (foo -> bar, f -> x).
To use it, pip install repren
. Check the README for examples.
回答6:
To replace a string in multiple files you can use:
grep -rl string1 somedir/ | xargs sed -i 's/string1/string2/g'
E.g.
grep -rl 'windows' ./ | xargs sed -i 's/windows/linux/g'
Source blog
回答7:
To replace a path within files (avoiding escape characters) you may use the following command:
sed -i 's@old_path@new_path@g'
The @ sign means that all of the special characters should be ignored in a following string.
回答8:
In case your string has a forward slash(/) in it, you could change the delimiter to '+'.
find . -type f -exec sed -i 's+http://example.com+https://example.com+g' {} +
This command would run recursively in the current directory.
回答9:
The first line occurrences of "foo" will be replaced with "bar". And you can using the second line to check.
grep -rl 'foo' . | xargs sed -i 's/foo/bar/g'
grep 'foo' -r * | awk -F: {'print $1'} | sort -n | uniq -c
回答10:
If you have list of files you can use
replace "old_string" "new_string" -- file_name1 file_name2 file_name3
If you have all files you can use
replace "old_string" "new_string" -- *
If you have list of files with extension, you can use
replace "old_string" "new_string" -- *.extension
回答11:
"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
" (Extracted from http://www.liamdelahunty.com/tips/linux_search_and_replace_multiple_files.php)
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' )
回答12:
I did concoct my own solution before I found this question (and answers). I searched for different combinations of "replace" "several" and "xml," because that was my application, but did not find this particular one.
My problem: I had spring xml files with data for test cases, containing complex objects. A refactor on the java source code changed a lot of classes and did not apply to the xml data files. In order to save the test cases data, I needed to change all the class names in all the xml files, distributed across several directories. All while saving backup copies of the original xml files (although this was not a must, since version control would save me here).
I was looking for some combination of find
+ sed
, because it worked for me in other situations, but not with several replacements at once.
Then I found ask ubuntu response and it helped me build my command line:
find -name "*.xml" -exec sed -s --in-place=.bak -e 's/firstWord/newFirstWord/g;s/secondWord/newSecondWord/g;s/thirdWord/newThirdWord/g' {} \;
And it worked perfectly (well, my case had six different replacements). But please note that it will touch all *.xml files under current directory. Because of that, and if you are accountable to a version control system, you might want to filter first and only pass on to sed
those actually having the strings you want; like:
find -name "*.xml" -exec grep -e "firstWord" -e "secondWord" -e "thirdWord" {} \; -exec sed -s --in-place=.bak -e 's/firstWord/newFirstWord/g;s/secondWord/newSecondWord/g;s/thirdWord/newThirdWord/g' {} \;
回答13:
grep --include={*.php,*.html} -rnl './' -e "old" | xargs -i@ sed -i 's/old/new/g' @
回答14:
script for multiedit command
multiedit [-n PATTERN] OLDSTRING NEWSTRING
From Kaspar's answer I made a bash script to accept command line arguments and optionally limit the filenames matching a pattern. Save in your $PATH and make executable, then just use the command above.
Here's the script:
#!/bin/bash
_help="\n
Replace OLDSTRING with NEWSTRING recursively starting from current directory\n
multiedit [-n PATTERN] OLDSTRING NEWSTRING\n
[-n PATTERN] option limits to filenames matching PATTERN\n
Note: backslash escape special characters\n
Note: enclose STRINGS with spaces in double quotes\n
Example to limit the edit to python files:\n
multiedit -n \*.py \"OLD STRING\" NEWSTRING\n"
# ensure correct number of arguments, otherwise display help...
if [ $# -lt 2 ] || [ $# -gt 4 ]; then echo -e $_help ; exit ; fi
if [ $1 == "-n" ]; then # if -n option is given:
# replace OLDSTRING with NEWSTRING recursively in files matching PATTERN
find ./ -type f -name "$2" -exec sed -i "s/$3/$4/g" {} \;
else
# replace OLDSTRING with NEWSTRING recursively in all files
find ./ -type f -exec sed -i "s/$1/$2/" {} \;
fi
回答15:
Really lame, but I couldn't get any of the sed commands to work right on OSX, so I did this dumb thing instead:
:%s/foo/bar/g
:wn
^- copy these three lines into my clipboard (yes, include the ending newline), then:
vi *
and hold down command-v until it says there's no files left.
Dumb...hacky...effective...
回答16:
The stream editor does modify multiple files “inplace” when invoked with the -i
switch, which takes a backup file ending as argument. So
sed -i.bak 's/foo/bar/g' *
replaces foo
with bar
in all files in this folder, but does not descend into subfolders. This will however generate a new .bak
file for every file in your directory.
To do this recursively for all files in this directory and all its subdirectories, you need a helper, like find
, to traverse the directory tree.
find ./ -print0 | xargs -0 sed -i.bak 's/foo/bar/g' *
find
allows you further restrictions on what files to modify, by specifying further arguments like find ./ -name '*.php' -or -name '*.html' -print0
, if necessary.
Note: GNU sed
does not require a file ending, sed -i 's/foo/bar/g' *
will work, as well; FreeBSD sed
demands an extension, but allows a space in between, so sed -i .bak s/foo/bar/g *
works.
回答17:
If the file contains backslashes (paths usually) you can try something like this:
sed -i -- 's,<path1>,<path2>,g' *
ex:
sed -i -- 's,/foo/bar,/new/foo/bar,g' *.sh (in all shell scripts available)
回答18:
To maintain my personal English node, I wrote an utility script that help to replace multiple pair of old/new string, for all files under a directory recursively.
The multiple pair of old / new string are managed in a hash map.
The dir can be set via command line or environment variable, the map is hard coded in the script, but you can modify the code to load from a file, if necessary.
It requires bash 4.2, due to some new feature.
en_standardize.sh:
#! /bin/bash
# (need bash 4.2+,)
#
# Standardize phonetic symbol of English.
#
# format:
# en_standardize.sh [<dir>]
#
# params:
# * dir
# target dir, optional,
# if not specified then use environment variable "$node_dir_en",
# if both not provided, then will not execute,
# *
#
paramCount=$#
# figure target dir,
if [ $paramCount -ge 1 ]; then # dir specified
echo -e "dir specified (in command):\n\t$1\n"
targetDir=$1
elif [[ -v node_dir_en ]]; then # environable set,
echo -e "dir specified (in environment vairable):\n\t$node_dir_en\n"
targetDir=$node_dir_en
else # environable not set,
echo "dir not specified, won't execute"
exit
fi
# check whether dir exists,
if [ -d $targetDir ]; then
cd $targetDir
else
echo -e "invalid dir location:\n\t$targetDir\n"
exit
fi
# initial map,
declare -A itemMap
itemMap=( ["ɪ"]="i" ["ː"]=":" ["ɜ"]="ə" ["ɒ"]="ɔ" ["ʊ"]="u" ["ɛ"]="e")
# print item maps,
echo 'maps:'
for key in "${!itemMap[@]}"; do
echo -e "\t$key\t->\t${itemMap[$key]}"
done
echo -e '\n'
# do replace,
for key in "${!itemMap[@]}"; do
grep -rli "$key" * | xargs -i@ sed -i "s/$key/${itemMap[$key]}/g" @
done
echo -e "\nDone."
exit
回答19:
Below command can be used to first search the files and replace the files
find . |xargs grep search string | sed 's/search string/new string/g'
e.g find . |xargs grep abc | sed 's/abc/xyz/g'
回答20:
I am giving an example for fixing a common shebang error in python sources.
You can try the grep/sed approach. Here is one that works with GNU sed and won't break a git repo:
$ grep -rli --exclude '*.git*' '#!/usr/bin/python' . | xargs -I {} \
gsed -i '' -e 's/#!\/usr\/bin\/python/#!\/usr\/bin\/env python/' {}
Or you can use greptile :)
$ greptile -x .py -l -i -g '#!/usr/bin/env python' -r '#!/usr/bin/python' .
I just tested the first script, and the second should work as well. Be careful with escape characters, I think it should be easier to use greptile in most cases. Of course, you can do many interesting things with sed, and for that it may be preferable to master using it with xargs.
回答21:
I found this one from another post (can't remember which) and while not the most elegant, it's simple and as a novice Linux user has given me no trouble
for i in *old_str* ; do mv -v "$i" "${i/\old_str/new_str}" ; done
if you have spaces or other special characters use a \
for i in *old_str\ * ; do mv -v "$i" "${i/\old_str\ /new_str}" ; done
for strings in sub-directories use **
for i in *\*old_str\ * ; do mv -v "$i" "${i/\old_str\ /new_str}" ; done
回答22:
$ replace "From" "To" -- `find /path/to/folder -type f`
(replace - a string-replacement utility of MySQL Database System)