bash 散列文本文件中的每一行

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5890136/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-17 23:56:35  来源:igfitidea点击:

hash each line in text file

bashcommand-linehash

提问by aaaa

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:

我正在尝试编写一个小脚本,它将打开一个文本文件并为每行文本提供一个 md5 哈希值。例如我有一个文件:

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:

我正在尝试在 bash 中执行此部分,它将读取每一行:

#!/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...

也许有更简单的方法......

回答by Lars Wiegman

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 printfor echo -ninstead of echooption.

除非您还想在每一行中散列换行符,否则您应该使用printfecho -n代替echo选项。

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.

可以使用多个文件作为参数调用该脚本。

回答by Wes Hardaker

You can just call md5sum directly in the script:

您可以直接在脚本中调用 md5sum :

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

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

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

这样脚本会直接输出您想要的内容:每行的 md5 哈希值。