chaîne - Extrait nom de fichier et l'extension dans Bash

Mots clés : bashstringfilenamesbashbash

meilleur 5 Réponses chaîne - Extrait nom de fichier et l'extension dans Bash

vote vote

95

filename=$(basename -- "$fullfile") extension="${filename##*.}" filename="${filename%.*}" 
filename="${fullfile##*/}" 
vote vote

84

~% FILE="example.tar.gz"  ~% echo "${FILE%%.*}" example  ~% echo "${FILE%.*}" example.tar  ~% echo "${FILE#*.}" tar.gz  ~% echo "${FILE##*.}" gz 
vote vote

70

basename filename .extension 
basename /path/to/dir/filename.txt .txt 
filename 
vote vote

62

bash-3.2$ FILENAME=somefile.tar.gz bash-3.2$ echo "${FILENAME%%.*}" somefile bash-3.2$ echo "${FILENAME%.*}" somefile.tar 
FULL_FILENAME=$FILENAME FILENAME=${FULL_FILENAME##*/} echo ${FILENAME%%.*} 
${variable%pattern}   Trim the shortest match from the end ${variable##pattern}   Trim the longest match from the beginning ${variable%%pattern}   Trim the longest match from the end ${variable#pattern}   Trim the shortest match from the beginning 
vote vote

51

#!/bin/bash for fullpath in "$@" do     filename="${fullpath##*/}"                      # Strip longest match of */ from start     dir="${fullpath:0:${#fullpath} - ${#filename}}" # Substring from 0 thru pos of filename     base="${filename%.[^.]*}"                       # Strip shortest match of . plus at least one non-dot char from end     ext="${filename:${#base} + 1}"                  # Substring from len of base thru end     if [[ -z "$base" && -n "$ext" ]]; then          # If we have an extension and no base, it's really the base         base=".$ext"         ext=""     fi      echo -e "$fullpath:\n\tdir  = \"$dir\"\n\tbase = \"$base\"\n\text  = \"$ext\"" done 
 $ basename-and-extension.sh / /home/me/ /home/me/file /home/me/file.tar /home/me/file.tar.gz /home/me/.hidden /home/me/.hidden.tar /home/me/.. . /:     dir  = "/"     base = ""     ext  = "" /home/me/:     dir  = "/home/me/"     base = ""     ext  = "" /home/me/file:     dir  = "/home/me/"     base = "file"     ext  = "" /home/me/file.tar:     dir  = "/home/me/"     base = "file"     ext  = "tar" /home/me/file.tar.gz:     dir  = "/home/me/"     base = "file.tar"     ext  = "gz" /home/me/.hidden:     dir  = "/home/me/"     base = ".hidden"     ext  = "" /home/me/.hidden.tar:     dir  = "/home/me/"     base = ".hidden"     ext  = "tar" /home/me/..:     dir  = "/home/me/"     base = ".."     ext  = "" .:     dir  = ""     base = "."     ext  = "" 

Questions similaires