HowTo: Bash Extract Filename And Extension In Unix / Linux

来源:互联网 发布:spring源码深度百度云 编辑:程序博客网 时间:2024/04/30 06:15

在Unix / Linux 下输出文件名


Find out filename

The syntax is as follows to remove the pattern (front of $VAR):

${var#Pattern}          ${var##Pattern} 

To get file name, enter:

dest="/nas100/backups/servers/z/zebra/mysql.tgz"echo "${dest##*/}"

OR

dest="/nas100/backups/servers/z/zebra/mysql.tgz"f="${dest##*/}"echo "${f}"

Sample outputs:

mysql.tgz

Find out file extension

The syntax is as follows to remove the pattern from back of $VAR:

dest="/nas100/backups/servers/z/zebra/mysql.tgz"echo "${dest##*.}"

OR

dest="/nas100/backups/servers/z/zebra/mysql.tgz"e="${dest##*.}"echo "${e}"

Sample outputs:
tgz

Extract filename i.e. filename without extension

The syntax is as follows to remove the pattern from back of $VAR:

${var%pattern}${var%%pattern}

To get filename without an extension, enter:

dest="/nas100/backups/servers/z/zebra/mysql.tgz"## get file name i.e. basename such as mysql.tgztempfile="${dest##*/}" ## display filename echo "${tempfile%.*}"

Sample outputs:

mysql

Putting it all together

#!/bin/bash## A sample shell script to demo concept of shell parameter expansion## Usage: backup.bash /path/to/backup.tar.gz ## Author: nixCraft <www.cyberciti.biz> under GPL v2.x+## ------------------------------------------------------------------- ## Get our script name ##_me="${0##*/}" ## get filename from cmd arg $1_backuppath="$1" ## Failsafe [[ $# -ne 1 ]] && { echo -en "Usage:\t$_me /path/to/file.tar\n\t$_me /path/to/file.tgz\n"; exit 1; } ## Backup these dirs _what="/etc /home /root" ## Get dirname _dirname="${_backuppath%/*}" # Get filename _filename="${_backuppath##*/}" # Get file extension _extesion="${_filename##*.}" # Set tar options_opt="" # Old backup file name starts with_oldsuff="old"  ## Okay log data to sysloglogger "$_me backup job started at $(date)@${HOSTNAME}" ## make decision based upon file extension[[ "$_extesion" == "tgz" ]] && { _opt="zcvf"; _oldpref="tgz"; }[[ "$_extesion" == "tar" ]] && { _opt="cvf"; _oldpref="tar";  }  ## Just display commands for demo purpose ##echo "tar $_opt /tmp/${_filename} $_what"echo "mv -f ${_backuppath} ${_dirname}/${_oldsuff}.${_filename%.*}.${_oldpref}"echo "cp -f /tmp/${_filename} ${_backuppath}" logger "$_me backup job ended at $(date)@${HOSTNAME}"

Run the script as follows:

backup.bash /backcup/data/server42/latest.tar

Sample outputs:

tar cvf /tmp/latest.tar /etc /home /rootmv -f /backcup/data/server42/latest.tar /backcup/data/server42/old.latest.tarcp -f /tmp/latest.tar /backcup/data/server42/latest.tar

Again run as follows:

backup.bash /backcup/data/server42/latest.tgz

Sample outputs:

tar zcvf /tmp/latest.tgz /etc /home /rootmv -f /backcup/data/server42/latest.tgz /backcup/data/server42/old.latest.tgzcp -f /tmp/latest.tgz /backcup/data/server42/latest.tgz

转载自:http://www.cyberciti.biz/faq/unix-linux-extract-filename-and-extension-in-bash/

0 0
原创粉丝点击