You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

Mac终端实现find、stat、md5单命令合并输出指定格式文件信息

Solution for Mac OS Terminal: Combine md5, stat, and find into Single-Line Output

First, let's break down why your previous attempts didn't work:

  • Your first command runs md5 and stat separately, so each outputs on its own line.
  • Case 1 failed because the backticks were evaluated by your shell before find replaced {}, so md5 tried to read a file literally named {}.
  • Case 2 used single quotes, which prevented the shell from executing the md5 command—so it just printed the raw string instead.

Single Command Solution

You can use find with a nested shell script to capture both outputs and combine them into one line per file. This handles filenames with spaces correctly too:

find . ! -empty -type f -exec sh -c '
    for file do
        md5_hash=$(md5 -q "$file")
        stat_details=$(stat -f "|%z|%SB|%N" "$file")
        echo "${md5_hash}${stat_details}"
    done
' sh {} +

How this works:

  • find passes all matching files to the nested shell script (using {} + for efficiency, which sends multiple files at once instead of one per shell instance).
  • The for file do loop iterates over each file passed in.
  • md5 -q "$file" gets the raw MD5 hash (no extra text).
  • stat -f "|%z|%SB|%N" "$file" generates the rest of the format string, starting with a pipe to connect to the MD5 hash.
  • We concatenate the two results and echo them as a single line.

Alternative: Simple Shell Script

If you prefer a reusable script instead of a one-liner, save this as file-info.sh:

#!/bin/bash

if [ $# -eq 0 ]; then
    echo "Usage: $0 <directory>"
    exit 1
fi

find "$1" ! -empty -type f -exec sh -c '
    for file do
        md5_hash=$(md5 -q "$file")
        stat_details=$(stat -f "|%z|%SB|%N" "$file")
        echo "${md5_hash}${stat_details}"
    done
' sh {} +

Then make it executable:

chmod +x file-info.sh

Run it with your target directory:

./file-info.sh .

Both methods will output exactly the format you want: MD5值|字节大小|修改日期|文件名 on a single line per file.

内容的提问来源于stack exchange,提问作者Victor Lam

火山引擎 最新活动