[英]sed - Remove parts of certain strings across multiple files
From the tutorial here , I learned to find and replace text across multiple files from the Linux command line. 从这里的教程中,我学会了从Linux命令行在多个文件中查找和替换文本。 For example, 例如,
find . -name "*.php" -print | xargs sed -i 's/foo/bar/g'
finds all instances of 'foo' in files that end with '.php' and replaces such instances with 'bar'. 在以“ .php”结尾的文件中查找“ foo”的所有实例,并将此类实例替换为“ bar”。
Now suppose I have multiple, redundant occurrences of something like assert something.makeAssertion
that I want to replace with just something.makeAssertion
. 现在,假设我有多个重复出现的东西,例如assert something.makeAssertion
,我只想替换为something.makeAssertion
。 Given that something
can vary, how do I adapt the script for this? 鉴于something
可能会有所不同,我该如何对此脚本进行调整? I tried some things with $
to capture something
as a variable (?) but haven't figured it out. 我尝试了一些事情$
捕捉到something
作为一个变量(?),但还没有想通了。
Superficially, you could use: 从表面上看,您可以使用:
find . -name '*.php' -exec \
sed -i.bak -e 's/assert\(.*\.makeAssertion\)/\1/g' {} +
The regex drops the assert
when there's a .makeAssertion
later on the line. 当稍后.makeAssertion
上有一个.makeAssertion
时,正则表达式会删除assert
。 The find … -exec
runs the sed
on the files it finds. find … -exec
在find … -exec
的文件上运行sed
。 The +
indicates 'group a convenient number of files into a single command line', rather like xargs
but without some complications. +
表示“将方便数量的文件分组到单个命令行中”,类似于xargs
但没有任何复杂性。 An alternative using GNU find
and xargs
would be: 使用GNU find
和xargs
的替代方法是:
find . -name '*.php' -print0 |
xargs -0 sed -i.bak -e 's/assert\(.*\.makeAssertion\)/\1/g'
Both these avoid problems with spaces or newlines in file names. 两者都避免了文件名中空格或换行符的问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.