在jpg文件中使用grep查找和替换



我一直在努力解决grep问题,试图扭转服务器范围内的黑客攻击,但grep在作为shell运行时似乎无法搜索jpg文件,但它自己的grep命令在ssh中工作。

这将返回良好的结果:grep-l-R"nastycode"/var/www/vhosts

,但当作为shell脚本运行时,它再也找不到jpg了

for file in $(grep -l -R "nastycode" /var/www/vhosts)
 do
  sed -e "s/"nastycode"/"nicecode"/ig" $file > /tmp/tempfile.tmp
  mv /tmp/tempfile.tmp $file
  echo "Modified: " $file
 done

Q: 这可能和"for file in"部分有关吗?Q: 在我们的搜索模式"nastycode"中,我们可以搜索具有regexp字符但将其视为正常字符($、|?等)的东西吗?

提前谢谢。

Nicholas

grep有一个选项,只要没有换行符,就可以忽略特殊字符(-F)。不幸的是,sed没有这样的选择。如果里面有特殊的字符,就必须将它们转义。如果其中有很多/,可以通过更改分隔符s|old|new|s@old@new@或代码中不包含的其他字符来避免对它们进行转义。关于结构的其余部分,我有几点意见。首先,你永远不应该使用for file in command结构,它会破坏空白;请使用**(您可能需要先使用shopt -s globstar启用它)或find。接下来,GNU sed有一个内联选项-i。您也可以为其指定备份后缀(例如-i.bak)。由于sed只有在找到模式时才会更改,因此实际上没有理由使用grep来限制文件。

把这些放在一起,(一旦你得到了regex转义-如果你需要的话,我们也可以帮助你)你可以使用这些:

# Globstar
for file in /var/www/vhosts/**; do
    sed -i.bak 's/) || stristr($ua/) &&false || stristr($ua/ig' $file
done
# find
find /var/www/vhosts -type f -exec sed -i.bak 's/) || stristr($ua/) &&false || stristr($ua/ig' {} ;
# If you really want the echo notification
find /var/www/vhosts -type f -exec grep -qiF ') || stristr($ua' {} ; -exec sed -i.bak 's/) || stristr($ua/) &&false || stristr($ua/ig' {} + -printf "Modified %pn"

最新更新