簡體   English   中英

如何編寫一個bash腳本來計算一個文件夾的所有文件的前n個字節的md5和

[英]How to write a bash script to calculate the md5 sum of the first n bytes of all files of a folder

我基本上在一個文件夾中有文件,我想為其計算 md5 總和。 但由於這需要很長時間,我想只獲取每個文件的前 n 個字節,並將其用作計算每個文件的 md5 總和的輸入。

如果一個文件夾中有兩個文件:

file1
file2

我想運行一個腳本,將以下內容輸出到終端:

file1 md5sum(first_n_bytes_of(./file1))
file2 md5sum(first_n_bytes_of(./file2))

我發現了幾個命令,它們似乎可以實現我想要的,但管道沒有按預期工作:

ls | head -c 16 | md5sum

ls -> lists all files
head -c 16 -> get first 16 bytes of inputfile
md5sum -> calculate md5sum

我只得到一個 MD5 值 output 盡管我在運行腳本的文件夾中有多個文件。 還有一個不需要/不需要的破折號。 輸出如下所示:

6221d61df4fbe4b0f7da2d7e030ada7f  -

另外如何將最后的 md5sum 與原始提供的文件名連接起來?

您可以遍歷文件,例如。

#!/usr/bin/env bash

shopt -s nullglob

for f in *; do
   chksum="$(md5sum < <(head -c16 "$f") ) $f"
   echo "$chksum"
done
  • nullglob bash shell 選項,如果在運行腳本的當前目錄中沒有文件,則不會擴展文字 glob *

  • for f in *循環遍歷當前目錄中的每個文件/文件夾*擴展到那個並且f是變量,請參閱echo *的 output

  • $( )稱為Command Substitution ,它捕獲內部任何命令的值,它通常用於將命令保存在此腳本中的變量中,在這種情況下, chksum是變量

  • <( )稱為過程替換

  • 要擴展bash中的變量,您需要在其前面添加一個$ ,並且 99.9% 的時間您也需要在其周圍加上引號。

  • Basically the script just loops to all the files/folders in the current working directory and ran md5sum and head on each and every one of them and save the output in a variable and lastly print() in python terminology and echo or printf in bash.

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM