Bash 脚本:在文件中用“X"替换字符;使用 sed 在两个给定字符串之间 [英] Bash script : in file replace characters with 'X" between two given strings using sed
问题描述
file=mylog.log
search_str="&Name="
end_str="&"
sed -i -E ':a; s/('"$search_str"'X*)[^X'"$end_str"']/\1X/; ta' "$file"
Ex 1:
something&Name=JASON&else
to
something&Name=XXXXX&else
实际上,如果我使用 '&' 而不是 '"$end_str"',我当前的 sed 命令可以正常工作性格...像这样:
And actually, my current sed command works fine when instead of a '"$end_str"' if I use '&' character... Like this :
sed -i -E ':a; s/('"$search_str"'X*)[^X&]/\1X/; ta' "$file"
所以,总而言之,它,在 ^X 之后,如果单个字符出现比我给定的 sed 命令工作正常...但相同的命令不起作用,如果我使用字符串代替字符...>
So, to summariz, it, after ^X if a single character comes than my given sed command works fine... But the same command does not work, if instead of character, i use a string...
For example, my sed command won't work in this case :
end_str="\%26"
sed -i -E ':a; s/('"$search_str"'X*)[^X'"$end_str"']/\1X/; ta' "$file"
例如:
something&Name=JASON_MATTHEW_DONALD%26else
TO
something&Name=XXXXXXXXXXXXXXXXXXXX%26else
例如:2
something&Name=JASON%26else
TO
something&Name=XXXXX%26else
请告诉我
推荐答案
我坚持认为在日志中保留密码的长度是一个非常糟糕的主意(安全方面).
I insist on the point that keeping the length of passwords in logs is a very bad idea (security wise).
话虽如此:
首先,字符列表[...]
不是匹配字符串的正确工具.为此,我们需要使用交替值 (...|...)
.
First, a character list [...]
is not the right tool to match an string. For that we need to use an alternating value (...|...)
.
end_str="(&|%26)"
但是在正则表达式中表达非字符串"是相当困难的.
But it is quite difficult to express a "not a string" in regex.
not_end_str="([^&]|[^%]|%[^2]|%2[^6])"
充分利用我们可能构建的纯 bash 解决方案(可能不快,但有效).
它打印到标准输出以显示它是如何工作的.重定向到文件以存储结果.
Using all that we may build a pure bash solution (maybe not fast, but works).
It prints to stdout to show how it works.
Redirect to a file to store the result.
file=mylog.log
search_str="&Name="
end_str="(&|%26)" # write end_str as an alternate value.
not_end_str="([^&]|[^%]|%[^2]|%2[^6])" # regex negate end_string.
# Build a regex that split each part of the text.
myreg="(.*${search_str}X*)(${not_end_str}*)([&%].*)"
while IFS=$'\n' read line; do
[[ $line =~ $myreg ]]
len=$((${#BASH_REMATCH[@]}-2)) # do not count [0] and last.
arr=("${BASH_REMATCH[@]:1}") # remove [0] and last.
arr[1]=${arr[1]//?/X} # Replace name with "X"'s.
arr[2]='' # Clear not_end_str match
printf '%s' "${arr[@]}"; echo # Print modified line.
done <"$file"
进一步阅读:
这篇关于Bash 脚本:在文件中用“X"替换字符;使用 sed 在两个给定字符串之间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!