Ubuntu – sha1sum of files in a directory

awkbashcommand lineprintingscripts

I have a script that returns the sha1sum of each file in a directory along with the full path of the file.

for i in /path/to/directory*.*; do sha1sum $i >> checksums.txt; done

Returns:

sha1sum  /path/to/directory/filename
sha1sum  /path/to/directory/filename2
sha1sum  /path/to/directory/filename3

How can I modify this such that the output contains only the sha1sum and the filename. I do not want to print the full path of the file.

I figure using sha1sum $i | awk '{print $1}' is the way to go but I do not know how to get only the file name

Best Answer

IMHO the simplest approach would be to change to the directory first, in a subshell:

(cd /path/to/directory ; for i in *.*; do sha1sum "$i" ; done) >> checksums.txt

Note that *.* only matches files with a 'dot extension' - to checksum all files, just use *


If you choose to go the awk route, then one approach would be to substitute the longest substring up to a / of the second field:

for i in /path/to/directory/*.*; do sha1sum $i ; done | awk '{sub(/.*\//,"",$2)} 1' >> checksums.txt