在bash脚本中使用perl命令搜索并替换多个文件中带有特殊字符的变量 [英] Search and replace variables with special characters in multiple files with perl command in a bash script
问题描述
尝试使用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@wR
和new_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.
-
参数
Arguments
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屋!