How to extract base64 code out of a file?



Dear members im having text file which contains 1 or 2 base64 blocks of code. Following is part of the file and 1 base64 block.

Content-Transfer-Encoding: base64


Being on Linux, which command i can do to extract first base64 out of the file? My aim is to decode output to be readable


Example file decode command:
Example phrasse decode command:

but i do not know how to extract only the base64 phrasse out of file which also contains non base64 contents.



I would normally do this in Perl using the MIME::Base64 module.

But you asked for a Linux command, and after a quick Google search, I found:

echo [encodedstring] | base64 --decode

from coreutils, or

openssl enc -base64 -d <<< [encodedstring]

using openssl (you will need the -A option if the input is more than 64 characters).

Either way, you will need to separate the MIME string from the rest of the text file to translate it.


you will need to separate the MIME string from the rest of the text file to translate it.
Yes, decoding is not the problem i also found commands, but that separation of non base64 and base64 thats what i dont know how to do ... as mentioned in my first post


Ah - you did say that. I was not paying close enough attention to your post - my fault!

From a command line, my thoughts seems convoluted - I tend to go to Perl for issues like this. It seems from your example you have a header and a trailer line, which makes the beginning and end of the MIME code easy to find programatically.

From a shell, you could use "wc -l" on the file to get the total number of lines, use

start=`awk '/header-text/{ print NR; exit }' input-file`

to get the line number where the text starts (or add 1 or more to the actual text), then do the same for the end line, and finally a combination of head and tail with some calculations of lines stringing them together, and pipe this into the decoder command.

This seems like a lot of work to me - there are ways of doing this with awk, but you are probably going to write an awk script to pass the file through.

I have done a fair amount of MIME encoding / decoding in Perl, so it just seems easier to me to write a small program to accept the file name as a parameter and print out the decoded MIME strings.

$0.02. Take this for what it's worth - my opinion.
$100 Digital Ocean Credit
Get a free VM to test out Linux!