Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

hash each line in text file

I'm trying to write a little script which will open a text file and give me an md5 hash for each line of text. For example I have a file with:

123
213
312

I want output to be:

ba1f2511fc30423bdbb183fe33f3dd0f
6f36dfd82a1b64f668d9957ad81199ff
390d29f732f024a4ebd58645781dfa5a

I'm trying to do this part in bash which will read each line:

#!/bin/bash
#read.file.line.by.line.sh

while read line
do
echo $line
done

later on I do:

$ more 123.txt | ./read.line.by.line.sh | md5sum | cut -d '  ' -f 1

but I'm missing something here, does not work :(

Maybe there is an easier way...

like image 356
aaaa Avatar asked May 04 '11 21:05

aaaa


2 Answers

Almost there, try this:

while read -r line; do printf %s "$line" | md5sum | cut -f1 -d' '; done < 123.txt

Unless you also want to hash the newline character in every line you should use printf or echo -n instead of echo option.

In a script:

#! /bin/bash
cat "$@" | while read -r line; do
    printf %s "$line" | md5sum | cut -f1 -d' '
done

The script can be called with multiple files as parameters.

like image 68
Lars Wiegman Avatar answered Oct 30 '22 12:10

Lars Wiegman


You can just call md5sum directly in the script:

#!/bin/bash
#read.file.line.by.line.sh

while read line
do
echo $line | md5sum | awk '{print $1}'
done

That way the script spits out directly what you want: the md5 hash of each line.

like image 36
Wes Hardaker Avatar answered Oct 30 '22 12:10

Wes Hardaker