base64 decoding in shell scripting

2019-08-18 05:20发布

问题:

For Example I have a file like as follows .

A,Y29tLz9hPTQ2JmM9NDQzNzgmczE9Q0,123  
B,FJNLTA2MjQyMDE3LVAmczI9ODQ3MDA,321

I want to print field1,field2(by base 64 decoding),field3

Output Required ::

A,result of base 64 decode,123
B,result of base 64 decode,321

回答1:

You can do this in a bash script with a few read commands and base64 -D:

#!/bin/bash

while read -r line
do
  IFS=',' read -r c1 c2 c3 <<< "$line"
  data="$(base64 -D <<< "$c2")"
  echo "$c1,$data,$c3"
done < "inputfile.txt"

Your one base64 strings has binary data in it though, so output may look funky due to control characters.

A,com/?a=46&c=44378&s1=,123
���KL
  �
�,321T  �̏N


回答2:

give this awk one-liner a try:

awk -F',' -v OFS=',' '"echo "$2" | base64" | getline $2' file

Test with your example:

kent$  cat f
A,Y29tLz9hPTQ2JmM9NDQzNzgmczE9Q0,123  
B,FJNLTA2MjQyMDE3LVAmczI9ODQ3MDA,321

kent$  awk -F',' -v OFS=',' '"echo "$2" | base64" | getline $2' f
A,WTI5dEx6OWhQVFEySm1NOU5EUXpOemdtY3pFOVEwCg==,123  
B,RkpOTFRBMk1qUXlNREUzTFZBbWN6STlPRFEzTURBCg==,321