将sed backreference传递给base64命令 [英] passing sed backreference to base64 command
问题描述
我想要实现的是将在sed
正则表达式中捕获的Base64编码值传递给base64
并对其进行解码.
What I am trying to achieve is pass the Base64 encoded value captured in the sed
regex to the base64
and have it decoded.
但是问题是,即使似乎使用反向引用将正确的值传递给了函数,base64
仍抱怨输入无效.
But the problem is, even though it seems like the correct value is being passed to the function using backreference, base64
complains that the input is invalid.
以下是我的脚本-
#!/bin/bash
decodeBaseSixtyFour() {
echo "$1 is decoded to `echo $1 | base64 -d`"
}
echo Passing direct value ...
echo SGVsbG8gQmFzZTY0Cg== | sed -r "s/(.+)$/$(decodeBaseSixtyFour SGVsbG8gQmFzZTY0Cg==)/"
echo Passing captured value ...
echo SGVsbG8gQmFzZTY0Cg== | sed -r "s/(.+)$/$(decodeBaseSixtyFour \\1)/"
运行时会产生以下输出-
And when ran it produces the following output -
Passing direct value ...
SGVsbG8gQmFzZTY0Cg== is decoded to Hello Base64
Passing captured value ...
base64: invalid input
SGVsbG8gQmFzZTY0Cg== is decoded to
我认为输出解释了我的意思.
I think the output explains what I mean.
是否有可能做我想做的事情?如果没有,为什么?
Is it possible to do what I am trying to do? If not, why?
推荐答案
Perl s///
可以满足您的要求,但我认为您所需要的不是您所需要的.
Perl s///
can do what you want, but I don't think what you're asking for is what you need.
$ echo SGVsbG8gQmFzZTY0Cg== | perl -MMIME::Base64 -pe 's/(.+)/decode_base64($1)/e'
Hello Base64
实际发生的事情:
echo SGVsbG8gQmFzZTY0Cg== | sed -r "s/(.+)$/$(decodeBaseSixtyFour \\1)/"
- 在sed开始读取输入之前,shell会在双引号引起来的字符串中注意到进程替换
- 使用字符串
"\\1"
调用 - base64在输入
\1
上阻塞,并发出错误消息 - 该函数返回字符串
"\1 is decoded to "
- 现在sed脚本是
's/(.+)$/\1 is decoded to /'
,这是您获得最后一行的方式. - Before sed starts reading input, the shell notices the process substitution in the double quoted string
- the
decodeBaseSixtyFour
function is called with the string"\\1"
- base64 chokes on the input
\1
and emits the error message - the function returns the string
"\1 is decoded to "
- now the sed script is
's/(.+)$/\1 is decoded to /'
which is how you get the last line.
decodeBaseSixtyFour
函数
这篇关于将sed backreference传递给base64命令的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!