我试图用sed做一些base64替换。Sed使用捕获组作为参数替换bash命令的输出
我想要做的是这样的:
sed -i "s|\(some\)\(pattern\)|\1 $(echo "\2" | base64 -d)|g" myFile
在英语中,这将是:
- 数学的模式
- 捕捉组
- 使用捕获组bash命令
- 使用此命令的输出作为替换字符串
到目前为止,我的命令不起作用,因为\2
只能由SED,而不是通过bash命令我打电话知道。
有什么优雅的解决方案,我必须将捕获组传递给我想要使用输出的命令?
编辑
这里是我想要做的一个小例子:
我有以下文件:
someline
someline
Base64Expression stringValue="Zm9v"
someline
Base64Expression stringValue="YmFy"
而且我想,以取代通过纯文本的base64:
someline
someline
Base64Expression stringValue="foo"
someline
Base64Expression stringValue="bar"
在未来,我必须做反向操作(该解码文件中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
这是不可能的,因为'$(echo“\ 2”| base64 -d)'是先完成的。此外,如果在sed中使用shell变量,则需要用双引号替换单引号。 – sjsam
'awk'是为这样的处理而设计的。但是,我们需要查看最小的一组样本数据以重现您的问题以及为了帮助您输入所需的输出。请编辑您的Q以包含该信息。祝你好运。 – shellter
@shellter我编辑了我用awk做过的问题。 @ sjsam,谢谢你指出我的引用,我也编辑了这个。 – statox