使用 sed 替换一些基于 64 位的编码字符串(调用外部 echo + base64)

using sed to replace some 64 based encoded strings (calling external echo + base64)

我正在使用 ldapsearch 查询 AD 服务器。一些结果是 64 位编码的(前面总是带有 ::),例如:

company: Medidata
company: Milestone
company:: QWRQIFNlcnZpw6dvcw==
company: ROFF

我可以手动解码这些编码字符串:

echo QWRQIFNlcnZpw6dvcw== | base64 -d

但我无法使用 sed 转换所有字符串(仅替换编码的字符串)。

这有效,但确实进行了替换。它仅用于调试。

cat output.txt | sed "s/:: \(.\+\)/: `echo \`/"
company: Medidata
company: Milestone
company: QWRQIFNlcnZpw6dvcw==
company: ROFF

我想做的是:

cat output.txt | sed "s/:: \(.\+\)/: `echo \ | base64 -d`/"
base64: invalid input
company: Medidata
company: Milestone
company: 
company: ROFF

base64 抱怨输入,但我觉得还不错。

我做错了什么?

使用 GNU sed 你可以使用 s///e:

$ cat file
company: Medidata
company: Milestone
company:: QWRQIFNlcnZpw6dvcw==
company: ROFF
$ cat file | gsed -E "s/(.*):: (.*)/printf %s '\1: '; echo '\2' | base64 -d/"
company: Medidata
company: Milestone
printf %s 'company: '; echo 'QWRQIFNlcnZpw6dvcw==' | base64 -d
company: ROFF
$ cat file | gsed -E "s/(.*):: (.*)/printf %s '\1: '; echo '\2' | base64 -d/e"
company: Medidata
company: Milestone
company: AdP Serviços
company: ROFF

doc s///e:

This command allows one to pipe input from a shell command into pattern space. If a substitution was made, the command that is found in pattern space is executed and pattern space is replaced with its output. A trailing newline is suppressed; results are undefined if the command to be executed contains a NUL character. This is a GNU sed extension.

使用 sed "s/:: \(.\+\)/: `echo \`/"sed "s/:: \(.\+\)/: `echo \ | base64 -d`/" 子 shell `...`sed 运行之前展开。因此 base64 抱怨它无法解码文字字符串 </code>.</p> <p>您必须指示 <code>sed(其语法与 bash 不同)才能调用外部程序。标准sed 不能调用外部程序。参见 How to embed a shell command into a sed expression?。但是 GNU sed 可以:

sed -E "s/(.*:): (.+)/printf %s ' '; echo '' | base64 -d/e"

这假定您要替换的行不包含任何 '。在你的情况下,我认为这应该不是问题。