grep – 将回车识别为新行

我想search一个运行unix的web服务器,它包含一个特定的string。 通常我使用这些命令来实现这一点:

find . -name "*.php" -print0 | xargs -0 grep -H -i "the string to search for" 

这将find任何包含“要search的string”的PHP文件,并打印文件名和匹配的行。

到目前为止,这工作得很好,但现在我遇到了一个服务器,所有的php脚本没有任何换行符,而是只有回车符。 grep似乎没有把回车看作是新行,所以上面的命令会打印一个文件的全部内容,如果里面有匹配的话,而不是只打印一行。

任何帮助将不胜感激!

如何使用(在我的Ubuntu上的grep,很确定大部分的grep在那里有这个标志)

  -o, --only-matching Print only the matched (non-empty) parts of a matching line, with each such >part on a separate output line. 

和…一起

  -b, --byte-offset Print the 0-based byte offset within the input file before each line of >output. If -o (--only-matching) is specified, print the offset of the matching part itself. 

然后你有文件名和你想要的部分。

另外,你是如何设法打破你的文件呢? 我试图用VI来replace换行符。 但是这使得grep和cat反而非常奇怪。

文件testing的内容

gggggggggggggggggggg ^ ^ Mggggggggasdfgggggggg Mgggggggggggggggggggg

〜/ test $ grep asdftesting

gggggggggggggggggggg

〜/testing$猫testing

gggggggggggggggggggg

在记事本中看起来很正常

不幸的是,grep不会做你想要的。 没有一个命令行选项让它将CR字符识别为行分隔符。 不过,你可以用awk来做你想做的事情! 尝试这个:

 find . -name '*.php' -print0 | \ xargs -0 awk -v RS="\r" '/string to search for/ {print FILENAME ": " $0}' 

awk几乎没有grep那么快,所以这个方法可能会花费很多时间,这取决于文件的数量和大小。 如果你要对它们进行大量的刷新,简单地转换你的PHP文件的所有行结束可能是值得的。 如果你没有一个方便的工具可以为你做这个,这个shell脚本应该这样做:

 find . -name '*.php' | while read PHPFILE; do mv "$PHPFILE" "$PHPFILE".orig awk -v RS="\r" '{print $0}' < "$PHPFILE".orig > "$PHPFILE" done 

如果你做这样的事情呢?

 for i in `find . -name "*.php" -print` ; do grep -H -i "the string to search for" $i 2>/dev/null >/dev/null ; if [ $? -eq 0 ] ; then echo $i ; fi ; done ; 

那么你只应该得到你正在寻找的文件的输出。