Skip to content
Advertisement

Decode base64 strings into hex strings in a file and overwrite

I have a list of base64 strings in a file (file.txt) that I need to convert into hex. E.g.,

6IwwfX8Cctn85LW+vItMhw==
wIsNfYESR9Nfueo7mg3f7Q==
A+MxnRyu6kotbKPZglQ0Fg==
Jt5jNIphpmfGoFgtgM7/Sg==
sN+Q0Xcu6JHlkqdhJlM/tw==

Command:

echo -n 6IwwfX8Cctn85LW+vItMhw== | base64 -d | od -t x1 -An

This command works individually (albeit the spaces in between), but I need to convert through each string in the file, which has more than 500 lines.

Basically, I want the above base64 string format to be decoded to the below example hex string format:

30aa268d130fb78a4f8cb6f300e4c760

Is there a way that I can call each line in the file (like a for each command) and pipe with the base64 command to convert? Any help is appreciated.

Advertisement

Answer

You can use Awk for this and run a command on the contents of the file using the getline() syntax

awk '{ cmd = "printf '%s' "$1 "| base64 -d | od -t x1 -An" }
     { while ( ( cmd | getline result ) > 0 ) { gsub(/[[:space:]]+/,"",result); $0 = result }; close(cmd)  }1' file.txt

Use a temporary file for overwriting the file contents and move back the original file

tmpfile=$(mktemp)
awk '{ cmd = "printf '%s' "$1 "| base64 -d | od -t x1 -An" }
     { while ( ( cmd | getline result ) > 0 ) { gsub(/[[:space:]]+/,"",result); $0 = result }; close(cmd)  }1' file.txt > "$tmpfile" && mv "$tmpfile" file.txt
User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement