我正在尝试使用sed进行一些base64替换.
我想要做的是这样的:
sed -i "s|\(some\)\(pattern\)|\1 $(echo "\2" | base64 -d)|g" myFile
Run Code Online (Sandbox Code Playgroud)
在英语中将是:
到目前为止,我的命令不起作用,因为\2
只有sed而不是我正在调用的bash命令才知道.
我有什么优雅的解决方案将捕获组传递给我想要使用输出的命令?
编辑
这是我正在尝试做的最小例子:
我有以下文件:
someline
someline
Base64Expression stringValue="Zm9v"
someline
Base64Expression stringValue="YmFy"
Run Code Online (Sandbox Code Playgroud)
我想用纯文本替换base64:
someline
someline
Base64Expression stringValue="foo"
someline
Base64Expression stringValue="bar"
Run Code Online (Sandbox Code Playgroud)
将来我将不得不做后向操作(在解码文件的base64中编码字符串)
我已经开始使用awk,但我可以使用sed更简单(更优雅).到目前为止,我有awk($bundle
我正在编辑的文件在哪里):
#For each line containing "Base64Expression"
#Put in the array $substitutions[]:
# The number of the line (NR)
# The encoded expression ($2)
# The decoded expression (x)
substitutions=($(awk -v bd=$bundle '
BEGIN {
# Change the separator from default
FS="""
ORS=","
OFS=","
}
/Base64Expression/ {
#Decode the base64 lines
cmd="echo -ne \""$2"\" | base64 -d"
cmd | getline x
if ( (cmd | getline) == 0 ){
print NR, $2, x
}
}
' $bundle))
# Substitute the encoded expressions by the decoded ones
# Use the entries of the array 3 by 3
# Create a sed command which takes the lines numbers
for ((i=0; i<${#substitutions[@]}; i+=3))
do
# Do the substitution only if the string is not empty
# Allows to handle properly the empty variables
if [ ${substitutions[$((i+1))]} ]
then
sed -i -e "${substitutions[$i]}s#${substitutions[$((i+1))]}#${substitutions[$((i+2))]}#" $bundle
fi
done
Run Code Online (Sandbox Code Playgroud)
fed*_*qui 14
您可以e
在GNU 中使用sed
替换字符串传递给shell进行评估.这样,你可以说:
printf "%s %s" "something" "\1"
Run Code Online (Sandbox Code Playgroud)
在哪里\1
举行被捕获的团体.全部一起:
$ sed -r 's#match_([0-9]*).*#printf "%s %s" "something" "\1"#e' <<< "match_555 hello"
something 555
Run Code Online (Sandbox Code Playgroud)
当您想要对捕获的组执行某些shell操作时,这很方便,就像在这种情况下一样.
所以,让我们捕捉线的第一部分,然后是需要编码的部分,最后是剩下的部分.完成后,让我们printf
打开这些碎片,触发base64 -d
对第二个切片的使用:
$ sed -r '/^Base64/s#(.*;)([^\&]*)(&.*)# printf "%s%s%s" "\1" $(echo "\2" | base64 -d) "\3";#e' file
someline
someline
Base64Expression stringValue="foo"
someline
Base64Expression stringValue="bar"
Run Code Online (Sandbox Code Playgroud)
一步步:
sed -r '/^Base64/s#(.*;)([^\&]*)(&.*)# printf "%s%s%s" "\1" $(echo "\2" | base64 -d) "\3";#e' file
# ^^^^^^^ ^^^ ^^^^^^ ^^^ ^^^^^^^^^^^^^^^^^^^^^^^^ ^
# | first part | the rest encode the 2nd captured group |
# | | |
# | important part execute the command
# |
# on lines starting with Base64, do...
Run Code Online (Sandbox Code Playgroud)
这个想法来自anubhava关于如何在sed中更改日期格式的精湛答案?.