我需要替换一个文件夹中的许多文件中的字符串,只有ssh访问服务器。我该怎么做呢?
当前回答
真的很蹩脚,但我不能让任何sed命令在OSX上工作,所以我做了这个愚蠢的事情:
:%s/foo/bar/g
:wn
^-复制这三行到我的剪贴板(是的,包括结束换行),然后:
vi *
按住command-v,直到它显示没有文件了。
愚蠢的…出租汽车司机…有效…
其他回答
类似于Kaspar的答案,但是用g标记来替换一行上的所有出现。
find ./ -type f -exec sed -i 's/old_string/new_string/g' {} \;
对于全局不区分大小写:
find ./ -type f -exec sed -i 's/old_string/new_string/gI' {} \;
有一个更简单的方法,使用一个简单的脚本文件:
# sudo chmod +x /bin/replace_string_files_present_dir
在gedit或你选择的编辑器中打开文件,我在这里使用gedit。
# sudo gedit /bin/replace_string_files_present_dir
然后在编辑器中将以下内容粘贴到文件中
#!/bin/bash
replace "oldstring" "newstring" -- *
replace "oldstring1" "newstring2" -- *
#add as many lines of replace as there are your strings to be replaced for
#example here i have two sets of strings to replace which are oldstring and
#oldstring1 so I use two replace lines.
保存文件,关闭gedit,然后退出您的终端,或者只是关闭它,然后启动它,以便能够加载您添加的新脚本。
导航到有多个要编辑的文件的目录。然后运行:
#replace_string_files_present_dir
按enter键,这将自动将包含它们的所有文件中的oldstring和oldstring1分别替换为正确的newstring和newstring1。
它将跳过不包含旧字符串的所有目录和文件。
如果您有多个目录的文件需要替换字符串,这可能有助于消除乏味的输入工作。你所要做的就是导航到这些目录,然后运行:
# replace_string_files_present_dir
你所要做的就是确保你已经包括或添加了所有替换字符串,就像我上面展示的那样:
替换 “oldstring” “newstring” -- *
在文件/bin/replace_string_files_present_dir的末尾。
要添加一个新的替换字符串,只需打开我们创建的脚本,在终端中输入以下命令:
Sudo gedit /bin/replace_string_files_present_dir
不要担心你添加的替换字符串的数量,如果没有找到oldstring,它们将没有任何影响。
要替换多个文件中的字符串,您可以使用:
grep -rl string1 somedir/ | xargs sed -i 's/string1/string2/g'
E.g.
grep -rl 'windows' ./ | xargs sed -i 's/windows/linux/g'
源的博客
@kev的答案很好,但只影响直接目录中的文件。下面的示例使用grep递归地查找文件。这对我来说每次都很有效。
grep -rli 'old-word' * | xargs -i@ sed -i 's/old-word/new-word/g' @
命令分解
Grep -r:——recursive,递归地读取每个目录下的所有文件。 Grep -l:——print-with-matches,打印每个有匹配项的文件的名称,而不是打印匹配行。 Grep -i:——忽略大小写。
xargs:将STDIN转换为参数,遵循这个答案。 Xargs -i@ ~命令包含@~:一个占位符,用于~命令中特定位置的参数,@符号是一个占位符,可以被任何字符串替换。
Sed -i:就地编辑文件,不进行备份。 Sed /regexp/replace /:替换匹配regexp的字符串。 Sed s/regexp/replacement/g: global,对每个匹配进行替换,而不是仅对第一个匹配进行替换。
我使用ag, the_silver_searcher:
ag -0 -l 'old' | xargs -0 sed -ri.bak -e 's/old/new/g';
然后git清除。bak文件(rm在git rebase exec中运行时出现bug)
git clean -f '**/*.bak';