Linux在文件和子目录中search

正确的需要一个脚本/命令,将列出所有.p​​hp文件,其中有一个模式/string。

它应该查看当前目录和所有子目录。

如果显示的行号是这样的,那就更好了:

my new command ./www/index.php Line 12 ./www/lib/config.php Line 123 

也有可能做一个search和replace每个文件中有这种模式的行?

grep可以自己做到这一点:

 grep -rn --include='*.php' "pattern" . 

找 。 -name'* .php'-print0 | xargs -0 grep -n“pattern”

我认为以下将search和replace,但要确保你先testing,因为我没有:-)

 find . -type f -name '*.php' -print0 | xargs -0 sed -i '.bak' -e 's/foo/bar/g' 

这将备份每个文件,然后通过创buildfilename.php.bak文件进行编辑,然后它将更新所有文件的时间戳。 它用'bar'代替'foo'。 对于包含空格的文件名也应该是安全的。

find . -name '*.php' |xargs -I{} perl -i.bak -pe 's/pattern/replacement/' {}

这确实find了每个php文件。 然后Xargs为STDIN上的每个input执行命令,将值传递给{} 。 然后Perl读取文件,用.bak扩展名重命名,并在文件的每一行执行Perlexpression式。

这不会取代模式吗?

找 。 -name“* .php”-exec sed -i“.bak”'s / pattern / replace / g'{} \;

虽然非常危险! 确保你保持独特的模式。 🙂

使用ack, 比grep好 。

优点(有关更多信息,请参阅使用ack而不是grep的十大理由):

  • searchrecursion默认情况下
  • 可以识别一组通用文件(–php)只searchphp文件
  • 支持Perl风格的正则expression式,因为它实际上是纯粹的Perl。
  • 默认为彩色

对于replace操作,您可以使用与Perl或Sed结合使用ack。