我有一个脚本,它返回目录中每个文件的 sha1sum 以及文件的完整路径。
for i in /path/to/directory*.*; do sha1sum $i >> checksums.txt; done
返回:
sha1sum /path/to/directory/filename
sha1sum /path/to/directory/filename2
sha1sum /path/to/directory/filename3
我该如何修改它,以便输出仅包含 sha1sum 和文件名。我不想打印文件的完整路径。
我认为使用sha1sum $i | awk '{print $1}'
是可行的方法,但我不知道如何仅获取文件名
答案1
我认为最简单的方法是先在子 shell 中更改目录:
(cd /path/to/directory ; for i in *.*; do sha1sum "$i" ; done) >> checksums.txt
请注意,*.*
仅匹配带有“点扩展名”的文件 - 进行校验和全部文件,只需使用*
如果您选择走这条awk
路线,那么一种方法是将sub
最长的子字符串替换为/
第二个字段:
for i in /path/to/directory/*.*; do sha1sum $i ; done | awk '{sub(/.*\//,"",$2)} 1' >> checksums.txt
答案2
只需使用find
带有标志的命令-exec
即可,如下所示:
$ find ./TESTDIR -type f -printf "%f\t" -exec bash -c 'sha256sum "$@" | awk "{print \$1}"' sh "{}" \;
out.txt cc29e205d04a4062d0fb131700e8bfc8e54c44d0176a8dca22f40b24ef26d325
2.txt f2ca1bb6c7e907d06dafe4687e579fce76b37e4e93b7605022da52e6ccc26fd2
with space.txt e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855
script.pl e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855
3.txt f2ca1bb6c7e907d06dafe4687e579fce76b37e4e93b7605022da52e6ccc26fd2
steam_locomotive e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855
storm carl e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855
1.txt f2ca1bb6c7e907d06dafe4687e579fce76b37e4e93b7605022da52e6ccc26fd2
sal e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855
simple_curl e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855
它的工作方式是,我们首先使用-printf "%f\t"
标志打印基本名称,然后在标志内执行 shell -exec
,并将实际文件路径作为命令行参数传递给 shell 本身。
虽然这看起来有点复杂,但它可以在传递给命令的任意路径上工作find
,因此不需要cd
绕过文件系统
可以使用上述命令的变体来实现更好的格式化,该命令反转-printf
和-exec
标志的位置:
$ find ./TESTDIR -type f -exec bash -c "sha256sum '{}' | awk '{printf \"%s\t\",\$1}' " \; -printf "%f\n"
cc29e205d04a4062d0fb131700e8bfc8e54c44d0176a8dca22f40b24ef26d325 out.txt
f2ca1bb6c7e907d06dafe4687e579fce76b37e4e93b7605022da52e6ccc26fd2 2.txt
e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855 with space.txt
e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855 script.pl
f2ca1bb6c7e907d06dafe4687e579fce76b37e4e93b7605022da52e6ccc26fd2 3.txt
e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855 steam_locomotive
e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855 storm carl
f2ca1bb6c7e907d06dafe4687e579fce76b37e4e93b7605022da52e6ccc26fd2 1.txt
e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855 sal
e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855 simple_curl