Skip to content
Advertisement

How to extract the directory from full file path

I have the following script which prints various file stats, which was kindly supplied by another user (choroba) (link).

Is there a way that this can be amended to report just the directory name of each file and not the full file path with the file name? I have tried changing filepath with dirname and I get a series of errors saying No such file or directory. Thanks for any advice.

#!/bin/bash
set -eu

filepath=$1
qfilepath=${filepath//\/\\}   # Quote backslashes.
qfilepath=${qfilepath//"/\"}  # Quote doublequotes.

file=${qfilepath##*/}            # Remove the path.

stats=($(stat -c "%s %W %Y" "$filepath"))
size=${stats[0]}
ctime=$(date --date @"${stats[1]}" +'%d/%m/%Y %H:%M:%S')
mtime=$(date --date @"${stats[2]}" +'%d/%m/%Y %H:%M:%S')

md5=$(md5sum < "$filepath")
md5=${md5%% *}                   # Remove the dash.

printf '"%s","%s",%s,%s,%s,%sn' 
        "$file" "$qfilepath" "$size" "$ctime" "$mtime" $md5

Advertisement

Answer

You can use a combination of dirname and basename, where:

dirname will strip the last component from the full path;

basename will get the last component from the path.

So to summarize: $(basename $(dirname $qfilepath)) will give you the name of the last directory in the path. Or, for the full path without the file name – just $(dirname $qfilepath).

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement