base64 each line of a file

Requirements are to parse a file to:

Here’s our test file (input.env):

AAAA=
BBBB=abc\ndef
CCCC=tuv$xyz
DDDD="with quotes"
EEEE=has-another=equals

Here’s the program:

# using: GNU awk 5.2.2, paste 9.3, sed 4.9, xargs 4.9.0
keysFile=$(mktemp)
sed "./input.env" \
  -e 's/=/\t/' \
  -e 's/\t.*//' \
  > "$keysFile"

valsFile=$(mktemp)
sed "./input.env" \
  -e 's/=/\t/' \
  -e 's/.*\t//' \
  | xargs -d'\n' -I'{}' bash -c "[ -z '{}' ] && echo || { echo -n '{}' | base64; }" \
  > "$valsFile"

finalFile=$(mktemp)
paste -d'=' "$keysFile" "$valsFile" > "$finalFile"
rm -f "$keysFile" "$valsFile"
cat "$finalFile"

General approach:

The output is

AAAA=
BBBB=YWJjXG5kZWY=
CCCC=dHV2JHh5eg==
DDDD=IndpdGggcXVvdGVzIg==
EEEE=aGFzLWFub3RoZXI9ZXF1YWxz

You can check the values are correct with echo YWJjXG5kZWY= | base64 -d and confirm they’re all identical to the input.

I was worried doing echo "$something" would run into issues with escaping, quotes, spaces, interpolation and all those other fun shell things. I search for a way to get each line of input to be fed to stdin of base64 and the closest I found was base64 <<< '{}', but it turns out the echo approach above works fine, so there was no need to stress about that.

comments powered by Disqus