[英]How to do a recursive find and replace from the command line?
Is there a simple way to recursively search all files in a directory hierarchy for a term (eg port
) and replace all occurrences of that term with another (eg port-lookup
). 是否有一种简单的方法可以递归搜索目录层次结构中的所有文件(例如
port
),并将该术语的所有匹配项替换为另一个(例如port-lookup
)。
I have tried the suggestions in this post , but they are only applicable for a single file. 我已尝试过这篇文章中的建议,但它们仅适用于单个文件。
Try this 尝试这个
find ./ -type f -exec sed -i -e 's/port/port-lookup/g' {} \;
If you don't want to change file modification time 如果您不想更改文件修改时间
grep -rl 'port' /search_in_this_dir | xargs sed -i 's/port/port-offset/g'
The simplest (and arguably most pure and intuitive) way to achieve this is to perform a recursive file grep
then pipe those file results to sed (via xargs
) to handle the in-place substitution. 实现此目的的最简单(也可以说是最纯粹和最直观)的方法是执行递归文件
grep
然后将这些文件结果传递给sed(通过xargs
)来处理就地替换。
grep -r -l "port" | xargs -r -d'\n' sed -i 's/port/port-lookup/g'
There is a comprehensive community wiki answer on this topic that I would recommend reading over on the Unix & Linux exchange.
关于这个主题有一个全面的社区wiki答案 ,我建议你阅读Unix和Linux交换。
If you have a recent version of bash (>4) 如果您有最新版本的bash(> 4)
shopt -s globstar
sed -i 's/port/port-lookup/g' **/*
Just 1 command line: msr -rp dir1,dir2,file1,fileN -x port -o port-lookup -R
只需1个命令行:
msr -rp dir1,dir2,file1,fileN -x port -o port-lookup -R
The above command recusively search and replaces plain text port
to port-lookup
in files. 上面的命令重复搜索并将纯文本
port
替换为文件中的port-lookup
。
-R
-R
-l
-l
-K
like -K -R
or -RK
. -K
如-K -R
或-RK
。 -i
like -i -x
or -ix
. -i
如-i -x
或-ix
。 C++
/ C#
/ Java
/ Scala
Regex syntax, use -t
instead of -x
. C++
/ C#
/ Java
/ Scala
Regex语法,请使用-t
而不是-x
。 -f "\\.(xml|java|cpp)$"
, exclude --nf "\\.(so|a|lib|dll|obj)$"
-f "\\.(xml|java|cpp)$"
,exclude --nf "\\.(so|a|lib|dll|obj)$"
-d "src"
, exclude --nd "^(target|\\.git)$"
-d "src"
,exclude --nd "^(target|\\.git)$"
--s1 1
/ --s1 1B
with/or --s2 1.20MB
--s1 1
/ --s1 1B
with /或--s2 1.20MB
--w1 2017-08-01
with/or --w2 "2017-08-12 11:20:30"
--w1 2017-08-01
with /或--w2 "2017-08-12 11:20:30"
More usages about find and replace file or pipe just see my open project https://github.com/qualiu/msr ( msr.exe
/ msr.gcc*
/ msr.cygwin
are in the tools
directory). 关于查找和替换文件或管道更多的用途只是看到我打开的项目https://github.com/qualiu/msr (
msr.exe
/ msr.gcc*
/ msr.cygwin
是在tools
目录)。 Built-in usage and exmaples just run the exe. 内置使用和exmaples只需运行exe。 Docs like performance comparision with findstr and grep .
Docs 与findstr和grep的性能比较 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.