Home > other >  How to decode base64 from each line in file in bash?
How to decode base64 from each line in file in bash?

Time:07-05

I have a file that contains many lines of base64 encoded text. I usually use base64 -d command to decode a single base64 string, but can I apply this command to each line in a file? Of course I can write a simple python script for this purpose, but I'm looking for more elegant and faster way using bash only. File contents example:

TEdVVURQT1NNS0FEQVZVWlZYTkQ=
V1dOUERXR0ZGT1VEUkdWTUFTQ1o=
U1NKV0pNSkVBSEtVU0hESEVWTkw=
Q0ZVTllUU05HUE9NR1dEV0lXSVY=
U1RZWVZOVE5ESUFVSUNBU1NNRU4=
SkhFQkJTQUhIWkxWSVBXS0VDSUI=
SE5GUFNVWU5YRVZVVktCWUZNS1E=
SUtZTlRCWFRKS0FFSEtNWlNWS0Q=
TVBSWlVKQU5BRlNDVE9JVkVDQ1A=
Q0hIT1ZOVVhQSFBGTlVUSERUQlQ=

CodePudding user response:

base64 -d will do what you want out of the box on my system:

$ echo one | base64  > file.txt
$ echo two | base64  >> file.txt
$ echo three | base64  >> file.txt

$ cat file.txt 
b25lCg==
dHdvCg==
dGhyZWUK

$ cat file.txt | base64 -d
one
two
three
$

Alternatively, using the highest voted bash for-line-in-file pattern:

$ cat file.txt | while read line ; do
    echo "$line" | base64 -d ; 
done

Will result in the same:

one
two
three
  • Related