使用 bash 脚本中的 perl 命令在多个文件中搜索和替换带有特殊字符的变量 [英] Search and replace variables with special characters in multiple files with perl command in a bash script

查看:13
本文介绍了使用 bash 脚本中的 perl 命令在多个文件中搜索和替换带有特殊字符的变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

尝试使用 bash 脚本中的 perl 命令在多个文件中搜索和替换带有特殊字符的密码变量.到目前为止,我有:

Trying to search and replace password variables with special characters in multiple files with a perl command in a bash script. So far I have:

grep -rlF "${old_pass}" | xargs perl -p -e "s~Q$old_pass~E$new_pass~g"

它适用于大多数情况,但有时会失败.例如,给定 old_pass=*DGB9Twq7WTwz@wRnew_pass=tDx6U&ShRv}E3Mdb 上面的命令导致 tDx6U&ShRv}E3Mdb@wR 而不仅仅是 tDx6U&ShRv}E3Mdb.

and it works for most cases, however sometimes it fails. For example, given old_pass=*DGB9Twq7WTwz@wR and new_pass=tDx6U&ShRv}E3Mdb the above command results in tDx6U&ShRv}E3Mdb@wR instead of just tDx6U&ShRv}E3Mdb.

请注意,密码是自动生成的,可以由所有大小写字母、数字和所有特殊字符组成.因此,工作版本必须能够考虑(转义)所有可能的密码版本.

Please note that passwords are generated automatically and can consist of all uppercase and lowercase letters, numbers and all special characters. So the working version must be able to take into account (escape) all kind of possible password versions.

推荐答案

您尝试生成正确的 Perl 代码但失败了.但真正的问题是您首先试图从 shell 生成 Perl 代码.在不使用 STDIN 或外部存储的情况下,可以通过三种主要方式将信息传递给 Perl.

You tried and failed to generate the correct Perl code. But the real problem is that you tried to generate Perl code form the shell in the first place. There are three primary ways of passing information to Perl without using STDIN or external storage.

  • 参数

perl -pe'BEGIN { ($o,$n)=splice(@ARGV,0,2) } s/Q$o/$n/g' -- "$old_pass" "$new_pass"

  • 命令行选项

  • Command-line options

    在完整的程序中,您将使用 Getopt::Long,但是 perl -s 在这里会很好.

    In a full program, you'd use Getopt::Long, but perl -s will do fine here.

    perl -spe's/Q$o/$n/g' -- -o="$old_pass" -n="$new_pass" --
    

  • 环境变量

  • Environment variables

    O="$old_pass" N="$new_pass" perl -pe's/Q$ENV{O}/$ENV{N}/g' --
    

    (在您的情况下,您必须为 xargs 而不是 perl 本身设置环境变量.)

    (In your case, you'd have to set the env vars for xargs instead of perl itself.)

    顺便说一句,您应该进一步限制您的正则表达式模式匹配的内容.就目前而言,您可能会出现误报.(匹配错误的用户密码.匹配密码的一部分.匹配根本不是密码的东西.)

    By the way, you should further restrict what your regex pattern matches. As it stands, you could have false positives. (Matching the wrong user's password. matching part of a password. Matching something that isn't a password at all.)

    这篇关于使用 bash 脚本中的 perl 命令在多个文件中搜索和替换带有特殊字符的变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

  • 查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆