Method #1: Use dirname command to get directory name
The syntax is:
dirname /path/to/file
OR
OR
FOO="/path/to/my/folder/filename.avi"
OUT="$(dirname ${FOO})"
OUT="$(dirname ${FOO})"
Examples
The following example displays output /nas01/data/backups:
dirname /nas01/data/backups/file.tar.gz
Sample outputs:
/nas01/data/backups
The following line sets the shell variable SRC to /nas01/data/backups:
SRC="$(dirname /nas01/data/backups/file.tar.gz)" echo "Dirpath - $SRC"
Sample outputs:
Dirpath - /nas01/data/backups
Method #2: Extract the directory name from a full path using bash/ksh shell
The $ character is used for parameter expansion, and command substitution. You can use it for manipulating and/or expanding variables on demands without using external commands such as sed or awk. To remove from shortest rear (end) pattern:
${VAR%/*} VAL="${PATHNAME%/*}"
In this example, set FILE to /nas01/data/backups/demo.avi:
FILE="/nas01/data/backups/demo.avi" echo "\$FILE = $FILE"
To extract the directory name, type:
echo "${FILE%/*}" # OR store to DIR # DIR="${FILE%/*}" echo "Dirpath - $DIR"
Sample outputs:
Dirpath - /nas01/data/backups
0 comments:
Post a Comment