使用 awk 使用 sha1sum 进行哈希

use*_*851 4 hash awk sha1 sed

我有一个“管道分隔”文件,大约有 20 列。我只想使用 sha1sum 对第一列进行哈希处理,该列是一个类似于帐号的数字,并按原样返回其余列。

使用 awk 或 sed 执行此操作的最佳方法是什么?

Accountid|Time|Category|.....
8238438|20140101021301|sub1|...
3432323|20140101041903|sub2|...
9342342|20140101050303|sub1|...
Run Code Online (Sandbox Code Playgroud)

上面是仅显示 3 列的文本文件示例。只有第一列实现了哈希函数。结果应该是这样的:

Accountid|Time|Category|.....
104a1f34b26ae47a67273fe06456be1fe97f75ba|20140101021301|sub1|...
c84270c403adcd8aba9484807a9f1c2164d7f57b|20140101041903|sub2|...
4fa518d8b005e4f9a085d48a4b5f2c558c8402eb|20140101050303|sub1|...
Run Code Online (Sandbox Code Playgroud)

Win*_*ute 5

最佳方式\xe2\x84\xa2 是什么还有待讨论。使用 awk 执行此操作的一种方法是

\n\n
awk -F\'|\' \'BEGIN { OFS=FS } NR == 1 { print } NR != 1 { gsub(/\'\\\'\'/, "\'\\\'\\\\\\\\\\\'\\\'\'", $1); command = ("echo \'\\\'\'" $1 "\'\\\'\' | sha1sum -b | cut -d\\\\  -f 1"); command | getline hash; close(command); $1 = hash; print }\' filename\n
Run Code Online (Sandbox Code Playgroud)\n\n

那是

\n\n
BEGIN {\n  OFS = FS          # set output field separator to field separator; we will use\n                    # it because we meddle with the fields.\n}\nNR == 1 {           # first line: just print headers.\n  print\n}\nNR != 1 {           # from there on do the hash/replace\n  # this constructs a shell command (and runs it) that echoes the field\n  # (singly-quoted to prevent surprises) through sha1sum -b, cuts out the hash\n  # and gets it back into awk with getline (into the variable hash)\n  # the gsub bit is to prevent the shell from barfing if there\'s an apostrophe\n  # in one of the fields.\n  gsub(/\'/, "\'\\\\\'\'", $1);\n  command = ("echo \'" $1 "\' | sha1sum -b | cut -d\\\\  -f 1")\n  command | getline hash\n  close(command)\n\n  # then replace the field and print the result.\n  $1 = hash\n  print\n}\n
Run Code Online (Sandbox Code Playgroud)\n\n

您会注意到顶部的 shell 命令和底部的 awk 代码之间的差异;这都是由于外壳膨胀造成的。因为我将 awk 代码放在 shell 命令中的单引号中(双引号在这种情况下没有争议,什么 with$1和 all),并且因为代码包含单引号,使其内联工作会导致反斜杠的噩梦。因此,我的建议是将 awk 代码放入一个文件中,例如foo.awk,然后运行

\n\n
awk -F\'|\' -f foo.awk filename\n
Run Code Online (Sandbox Code Playgroud)\n\n

反而。

\n