散列文本文件每一行的最有效方法?
Most efficient way to hash each line of a text file?
我目前正在编写一个 Bash 脚本,该脚本对文本文件的每一行进行哈希处理,并将其输出到格式为 hash:orginalword
的新文件中。我目前执行此操作的脚本是:
cat $originalfile | while read -r line; do
hash="$(printf %s "$line" | $hashfunction | cut -f1 -d' ')"
echo "$hash:$line" >> $outputlocation
done
我最初是从链接的一个非常相似的问题 here 中获得代码的。该脚本完全按照宣传的方式工作;然而,问题在于,即使是非常小的文本文件 (<15KB),也需要很长时间来处理。
如果有人能推荐一个实现完全相同结果但效率更高的脚本,我将不胜感激。
提前感谢您的帮助,
亲切的问候,约翰
您可以将文件每行拆分为一个文件,并在一次调用中完成:
$ cat > words.txt << EOF
> foo
> bar
> baz
> EOF
$ split --lines=1 words.txt
$ sha256sum x*
b5bb9d8014a0f9b1d61e21e796d78dccdf1352f23cd32812f4850b878ae4944c xaa
7d865e959b2466918c9863afca942d0fb89d7c9ac0c99bafc3749504ded97730 xab
bf07a7fbb825fc0aae7bf4a1177b2b31fcf8a3feeaf7092761e18c859ee52a9c xac
如果纯粹 shell 这样做,我会非常谨慎。为每一行启动散列函数的开销将使它在大文件上非常慢。
学一点 Perl 怎么样?
perl -MDigest::MD5 -nle 'print Digest::MD5::md5_hex($_), ":", $_' <$originalfile >>$outputlocation
Perl 有多种 Digest
模块,所以比 MD5 更容易使用。
perl -MDigest::SHA -nle 'print Digest::SHA::sha256_hex($_), ":", $_' <$originalfile >>$outputlocation
如果你想使用 Whirlpool,你可以使用
从 CPAN 安装它
cpan install Digest::Whirlpool
并与
一起使用
perl -MDigest -nle '$ctx = Digest->new("Whirlpool"); $ctx->add($_); print $ctx->hexdigest(), ":", $_' <$originalfile >>$outputlocation
我目前正在编写一个 Bash 脚本,该脚本对文本文件的每一行进行哈希处理,并将其输出到格式为 hash:orginalword
的新文件中。我目前执行此操作的脚本是:
cat $originalfile | while read -r line; do
hash="$(printf %s "$line" | $hashfunction | cut -f1 -d' ')"
echo "$hash:$line" >> $outputlocation
done
我最初是从链接的一个非常相似的问题 here 中获得代码的。该脚本完全按照宣传的方式工作;然而,问题在于,即使是非常小的文本文件 (<15KB),也需要很长时间来处理。
如果有人能推荐一个实现完全相同结果但效率更高的脚本,我将不胜感激。
提前感谢您的帮助,
亲切的问候,约翰
您可以将文件每行拆分为一个文件,并在一次调用中完成:
$ cat > words.txt << EOF
> foo
> bar
> baz
> EOF
$ split --lines=1 words.txt
$ sha256sum x*
b5bb9d8014a0f9b1d61e21e796d78dccdf1352f23cd32812f4850b878ae4944c xaa
7d865e959b2466918c9863afca942d0fb89d7c9ac0c99bafc3749504ded97730 xab
bf07a7fbb825fc0aae7bf4a1177b2b31fcf8a3feeaf7092761e18c859ee52a9c xac
如果纯粹 shell 这样做,我会非常谨慎。为每一行启动散列函数的开销将使它在大文件上非常慢。
学一点 Perl 怎么样?
perl -MDigest::MD5 -nle 'print Digest::MD5::md5_hex($_), ":", $_' <$originalfile >>$outputlocation
Perl 有多种 Digest
模块,所以比 MD5 更容易使用。
perl -MDigest::SHA -nle 'print Digest::SHA::sha256_hex($_), ":", $_' <$originalfile >>$outputlocation
如果你想使用 Whirlpool,你可以使用
从 CPAN 安装它cpan install Digest::Whirlpool
并与
一起使用perl -MDigest -nle '$ctx = Digest->new("Whirlpool"); $ctx->add($_); print $ctx->hexdigest(), ":", $_' <$originalfile >>$outputlocation