2491

我想分别获取文件名(不带扩展名)和扩展名。

到目前为止我发现的最佳解决方案是:

NAME=`echo "$FILE" | cut -d'.' -f1`
EXTENSION=`echo "$FILE" | cut -d'.' -f2`

.这是错误的,因为如果文件名包含多个字符,它就不起作用。如果,假设我有a.b.js,它将考虑aand b.js,而不是a.band js

它可以很容易地在 Python 中完成

file, ext = os.path.splitext(path)

但如果可能的话,我不希望为此启动 Python 解释器。

有更好的想法吗?

4

38 回答 38

4014

首先,获取不带路径的文件名:

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

或者,您可以关注路径的最后一个“/”而不是“。” 即使您有不可预测的文件扩展名,它也应该工作:

filename="${fullfile##*/}"

您可能需要查看文档:

于 2009-06-08T14:05:19.073 回答
917
~% FILE="example.tar.gz"

~% echo "${FILE%%.*}"
example

~% echo "${FILE%.*}"
example.tar

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

~% echo "${FILE##*.}"
gz

更多详细信息,请参阅Bash 手册中的shell 参数扩展

于 2009-06-08T14:05:13.083 回答
543

通常您已经知道扩展名,因此您可能希望使用:

basename filename .extension

例如:

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

我们得到

filename
于 2011-10-19T10:56:09.373 回答
181

您可以使用 POSIX 参数扩展的魔力:

bash-3.2$ FILENAME=somefile.tar.gz
bash-3.2$ echo "${FILENAME%%.*}"
somefile
bash-3.2$ echo "${FILENAME%.*}"
somefile.tar

需要注意的是,如果您的文件名是格式,./somefile.tar.gz那么echo ${FILENAME%%.*}会贪婪地删除最长的匹配项,.并且您将获得空字符串。

(您可以使用临时变量解决此问题:

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
于 2013-02-05T09:09:58.277 回答
87

如果文件没有扩展名或没有文件名,这似乎不起作用。这是我正在使用的;它只使用内置函数并处理更多(但不是全部)病态文件名。

#!/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/..
/:
    目录 = "/"
    基数 = ""
    分机 = ""
/家/我/:
    目录=“/家/我/”
    基数 = ""
    分机 = ""
/家/我/文件:
    目录=“/家/我/”
    基地=“文件”
    分机 = ""
/home/me/file.tar:
    目录=“/家/我/”
    基地=“文件”
    分机=“焦油”
/home/me/file.tar.gz:
    目录=“/家/我/”
    基地=“文件.tar”
    分机=“gz”
/home/me/.hidden:
    目录=“/家/我/”
    基数 = “.hidden”
    分机 = ""
/home/me/.hidden.tar:
    目录=“/家/我/”
    基数 = “.hidden”
    分机=“焦油”
/家/我/..:
    目录=“/家/我/”
    基地=“..”
    分机 = ""
.:
    目录 = ""
    基地=“。”
    分机 = ""
于 2009-09-10T05:17:16.777 回答
64
pax> echo a.b.js | sed 's/\.[^.]*$//'
a.b
pax> echo a.b.js | sed 's/^.*\.//'
js

工作正常,所以你可以使用:

pax> FILE=a.b.js
pax> NAME=$(echo "$FILE" | sed 's/\.[^.]*$//')
pax> EXTENSION=$(echo "$FILE" | sed 's/^.*\.//')
pax> echo $NAME
a.b
pax> echo $EXTENSION
js

顺便说一下,这些命令的工作方式如下。

for 的命令NAME替换一个"."字符,后跟任意数量的非"."字符,直到行尾,什么都没有(即,它删除从"."行尾到行尾的所有内容,包括在内)。这基本上是使用正则表达式技巧的非贪婪替换。

的命令EXTENSION替换任意数量的字符,后跟一个"."字符在行的开头,什么都没有(即,它删除从行的开头到最后一个点的所有内容,包括在内)。这是一个贪婪的替换,它是默认操作。

于 2009-06-08T14:14:37.433 回答
50

您可以使用basename.

例子:

$ basename foo-bar.tar.gz .tar.gz
foo-bar

您确实需要为 basename 提供将被删除的扩展名,但是如果您总是执行tar-z那么您知道扩展名将是.tar.gz.

这应该做你想要的:

tar -zxvf $1
cd $(basename $1 .tar.gz)
于 2013-02-05T08:50:17.440 回答
41

梅伦在一篇博文的评论中写道:

使用 Bash,还${file%.*}可以获取不带扩展名的文件名并${file##*.}单独获取扩展名。那是,

file="thisfile.txt"
echo "filename: ${file%.*}"
echo "extension: ${file##*.}"

输出:

filename: thisfile
extension: txt
于 2010-07-21T10:24:37.820 回答
32

无需费心,甚至awk无需为这个简单的任务而烦恼。有一个纯 Bash兼容的解决方案,它只使用参数扩展。sedperlos.path.splitext()

参考实现

文档os.path.splitext(path)

将路径名路径拆分为一对(root, ext),使得root + ext == path, 和ext为空或以句点开头且最多包含一个句点。基本名称上的前导句点被忽略;splitext('.cshrc')返回('.cshrc', '')

Python代码:

root, ext = os.path.splitext(path)

Bash 实现

表彰领先时期

root="${path%.*}"
ext="${path#"$root"}"

忽略领先时期

root="${path#.}";root="${path%"$root"}${root%.*}"
ext="${path#"$root"}"

测试

以下是忽略前导句点实现的测试用例,它应该与每个输入上的 Python 参考实现相匹配。

|---------------|-----------|-------|
|path           |root       |ext    |
|---------------|-----------|-------|
|' .txt'        |' '        |'.txt' |
|' .txt.txt'    |' .txt'    |'.txt' |
|' txt'         |' txt'     |''     |
|'*.txt.txt'    |'*.txt'    |'.txt' |
|'.cshrc'       |'.cshrc'   |''     |
|'.txt'         |'.txt'     |''     |
|'?.txt.txt'    |'?.txt'    |'.txt' |
|'\n.txt.txt'   |'\n.txt'   |'.txt' |
|'\t.txt.txt'   |'\t.txt'   |'.txt' |
|'a b.txt.txt'  |'a b.txt'  |'.txt' |
|'a*b.txt.txt'  |'a*b.txt'  |'.txt' |
|'a?b.txt.txt'  |'a?b.txt'  |'.txt' |
|'a\nb.txt.txt' |'a\nb.txt' |'.txt' |
|'a\tb.txt.txt' |'a\tb.txt' |'.txt' |
|'txt'          |'txt'      |''     |
|'txt.pdf'      |'txt'      |'.pdf' |
|'txt.tar.gz'   |'txt.tar'  |'.gz'  |
|'txt.txt'      |'txt'      |'.txt' |
|---------------|-----------|-------|

测试结果

所有测试都通过了。

于 2016-12-02T09:04:43.557 回答
27

您可以使用该cut命令删除最后两个扩展名(".tar.gz"部分):

$ echo "foo.tar.gz" | cut -d'.' --complement -f2-
foo

正如克莱顿休斯在评论中指出的那样,这不适用于问题中的实际示例。因此,作为替代方案,我建议使用sed扩展正则表达式,如下所示:

$ echo "mpc-1.0.1.tar.gz" | sed -r 's/\.[[:alnum:]]+\.[[:alnum:]]+$//'
mpc-1.0.1

它通过无条件地删除最后两个(字母数字)扩展来工作。

[在安德斯·林达尔发表评论后再次更新]

于 2013-02-05T08:53:11.740 回答
25

接受的答案在典型情况下效果很好,但在边缘情况下失败,即:

  • 对于没有扩展名的文件名(在此答案的其余部分中称为后缀extension=${filename##*.}),返回输入文件名而不是空字符串。
  • extension=${filename##*.}不包括首字母.,违反约定。
    • 对于没有后缀的文件名,盲目地前置.是行不通的。
  • filename="${filename%.*}"将是空字符串,如果输入文件名以开头.并且不包含其他.字符(例如,.bash_profile) - 与约定相反。

---------

因此,涵盖所有边缘情况的强大解决方案的复杂性需要一个函数- 请参见下面的定义;它可以返回路径的所有组件。

示例调用:

splitPath '/etc/bash.bashrc' dir fname fnameroot suffix
# -> $dir == '/etc'
# -> $fname == 'bash.bashrc'
# -> $fnameroot == 'bash'
# -> $suffix == '.bashrc'

请注意,输入路径之后的参数是自由选择的,位置变量名称
要跳过那些之前不感兴趣的变量,请指定_(使用一次性变量$_)或'';例如,要仅提取文件名根和扩展名,请使用splitPath '/etc/bash.bashrc' _ _ fnameroot extension.


# SYNOPSIS
#   splitPath path varDirname [varBasename [varBasenameRoot [varSuffix]]] 
# DESCRIPTION
#   Splits the specified input path into its components and returns them by assigning
#   them to variables with the specified *names*.
#   Specify '' or throw-away variable _ to skip earlier variables, if necessary.
#   The filename suffix, if any, always starts with '.' - only the *last*
#   '.'-prefixed token is reported as the suffix.
#   As with `dirname`, varDirname will report '.' (current dir) for input paths
#   that are mere filenames, and '/' for the root dir.
#   As with `dirname` and `basename`, a trailing '/' in the input path is ignored.
#   A '.' as the very first char. of a filename is NOT considered the beginning
#   of a filename suffix.
# EXAMPLE
#   splitPath '/home/jdoe/readme.txt' parentpath fname fnameroot suffix
#   echo "$parentpath" # -> '/home/jdoe'
#   echo "$fname" # -> 'readme.txt'
#   echo "$fnameroot" # -> 'readme'
#   echo "$suffix" # -> '.txt'
#   ---
#   splitPath '/home/jdoe/readme.txt' _ _ fnameroot
#   echo "$fnameroot" # -> 'readme'  
splitPath() {
  local _sp_dirname= _sp_basename= _sp_basename_root= _sp_suffix=
    # simple argument validation
  (( $# >= 2 )) || { echo "$FUNCNAME: ERROR: Specify an input path and at least 1 output variable name." >&2; exit 2; }
    # extract dirname (parent path) and basename (filename)
  _sp_dirname=$(dirname "$1")
  _sp_basename=$(basename "$1")
    # determine suffix, if any
  _sp_suffix=$([[ $_sp_basename = *.* ]] && printf %s ".${_sp_basename##*.}" || printf '')
    # determine basename root (filemane w/o suffix)
  if [[ "$_sp_basename" == "$_sp_suffix" ]]; then # does filename start with '.'?
      _sp_basename_root=$_sp_basename
      _sp_suffix=''
  else # strip suffix from filename
    _sp_basename_root=${_sp_basename%$_sp_suffix}
  fi
  # assign to output vars.
  [[ -n $2 ]] && printf -v "$2" "$_sp_dirname"
  [[ -n $3 ]] && printf -v "$3" "$_sp_basename"
  [[ -n $4 ]] && printf -v "$4" "$_sp_basename_root"
  [[ -n $5 ]] && printf -v "$5" "$_sp_suffix"
  return 0
}

test_paths=(
  '/etc/bash.bashrc'
  '/usr/bin/grep'
  '/Users/jdoe/.bash_profile'
  '/Library/Application Support/'
  'readme.new.txt'
)

for p in "${test_paths[@]}"; do
  echo ----- "$p"
  parentpath= fname= fnameroot= suffix=
  splitPath "$p" parentpath fname fnameroot suffix
  for n in parentpath fname fnameroot suffix; do
    echo "$n=${!n}"
  done
done

执行该功能的测试代码:

test_paths=(
  '/etc/bash.bashrc'
  '/usr/bin/grep'
  '/Users/jdoe/.bash_profile'
  '/Library/Application Support/'
  'readme.new.txt'
)

for p in "${test_paths[@]}"; do
  echo ----- "$p"
  parentpath= fname= fnameroot= suffix=
  splitPath "$p" parentpath fname fnameroot suffix
  for n in parentpath fname fnameroot suffix; do
    echo "$n=${!n}"
  done
done

预期输出 - 注意边缘情况:

  • 没有后缀的文件名
  • .以(被视为后缀的开头) 开头的文件名
  • 以(忽略/尾随)结尾的输入路径/
  • 仅作为文件名的输入路径(.作为父路径返回)
  • 具有多个.-prefixed 标记的文件名(仅最后一个被视为后缀):
----- /etc/bash.bashrc
parentpath=/etc
fname=bash.bashrc
fnameroot=bash
suffix=.bashrc
----- /usr/bin/grep
parentpath=/usr/bin
fname=grep
fnameroot=grep
suffix=
----- /Users/jdoe/.bash_profile
parentpath=/Users/jdoe
fname=.bash_profile
fnameroot=.bash_profile
suffix=
----- /Library/Application Support/
parentpath=/Library
fname=Application Support
fnameroot=Application Support
suffix=
----- readme.new.txt
parentpath=.
fname=readme.new.txt
fnameroot=readme.new
suffix=.txt
于 2013-08-09T03:45:30.657 回答
24

以下是一些替代建议(主要在 中awk),包括一些高级用例,例如提取软件包的版本号。

f='/path/to/complex/file.1.0.1.tar.gz'

# Filename : 'file.1.0.x.tar.gz'
    echo "$f" | awk -F'/' '{print $NF}'

# Extension (last): 'gz'
    echo "$f" | awk -F'[.]' '{print $NF}'

# Extension (all) : '1.0.1.tar.gz'
    echo "$f" | awk '{sub(/[^.]*[.]/, "", $0)} 1'

# Extension (last-2): 'tar.gz'
    echo "$f" | awk -F'[.]' '{print $(NF-1)"."$NF}'

# Basename : 'file'
    echo "$f" | awk '{gsub(/.*[/]|[.].*/, "", $0)} 1'

# Basename-extended : 'file.1.0.1.tar'
    echo "$f" | awk '{gsub(/.*[/]|[.]{1}[^.]+$/, "", $0)} 1'

# Path : '/path/to/complex/'
    echo "$f" | awk '{match($0, /.*[/]/, a); print a[0]}'
    # or 
    echo "$f" | grep -Eo '.*[/]'

# Folder (containing the file) : 'complex'
    echo "$f" | awk -F'/' '{$1=""; print $(NF-1)}'

# Version : '1.0.1'
    # Defined as 'number.number' or 'number.number.number'
    echo "$f" | grep -Eo '[0-9]+[.]+[0-9]+[.]?[0-9]?'

    # Version - major : '1'
    echo "$f" | grep -Eo '[0-9]+[.]+[0-9]+[.]?[0-9]?' | cut -d. -f1

    # Version - minor : '0'
    echo "$f" | grep -Eo '[0-9]+[.]+[0-9]+[.]?[0-9]?' | cut -d. -f2

    # Version - patch : '1'
    echo "$f" | grep -Eo '[0-9]+[.]+[0-9]+[.]?[0-9]?' | cut -d. -f3

# All Components : "path to complex file 1 0 1 tar gz"
    echo "$f" | awk -F'[/.]' '{$1=""; print $0}'

# Is absolute : True (exit-code : 0)
    # Return true if it is an absolute path (starting with '/' or '~/'
    echo "$f" | grep -q '^[/]\|^~/'

所有用例都使用原始完整路径作为输入,而不依赖于中间结果。

于 2015-06-16T09:02:52.587 回答
22

最小和最简单的解决方案(单行)是:

$ file=/blaabla/bla/blah/foo.txt
echo $(basename ${file%.*}) # foo
于 2017-04-22T14:39:16.063 回答
18

我认为如果你只需要文件名,你可以试试这个:

FULLPATH=/usr/share/X11/xorg.conf.d/50-synaptics.conf

# Remove all the prefix until the "/" character
FILENAME=${FULLPATH##*/}

# Remove all the prefix until the "." character
FILEEXTENSION=${FILENAME##*.}

# Remove a suffix, in our case, the filename. This will return the name of the directory that contains this file.
BASEDIRECTORY=${FULLPATH%$FILENAME}

echo "path = $FULLPATH"
echo "file name = $FILENAME"
echo "file extension = $FILEEXTENSION"
echo "base directory = $BASEDIRECTORY"

这就是全部=D。

于 2011-09-29T07:26:47.640 回答
13

您可以强制剪切以显示所有字段以及添加-到字段编号的后续字段。

NAME=`basename "$FILE"`
EXTENSION=`echo "$NAME" | cut -d'.' -f2-`

因此,如果 FILE 是eth0.pcap.gz,则 EXTENSION 将是pcap.gz

使用相同的逻辑,您还可以使用带有 cut 的 '-' 获取文件名,如下所示:

NAME=`basename "$FILE" | cut -d'.' -f-1`

这甚至适用于没有任何扩展名的文件名。

于 2012-09-10T13:46:00.813 回答
10

魔术文件识别

除了关于这个 Stack Overflow 问题的很多好的答案,我想补充一下:

在 Linux 和其他 unixen 下,有一个名为 的魔术命令file,它通过分析文件的一些首字节来进行文件类型检测。这是一个非常古老的工具,最初用于打印服务器(如果不是为......我不确定)。

file myfile.txt
myfile.txt: UTF-8 Unicode text

file -b --mime-type myfile.txt
text/plain

可以在以下位置找到标准扩展/etc/mime.types(在我的Debian GNU/Linux 桌面上。请参阅man fileman mime.types。也许您必须安装file实用程序和mime-support软件包):

grep $( file -b --mime-type myfile.txt ) </etc/mime.types
text/plain      asc txt text pot brf srt

您可以创建一个函数来确定正确的扩展名。有一个小(不完美)示例:

file2ext() {
    local _mimetype=$(file -Lb --mime-type "$1") _line _basemimetype
    case ${_mimetype##*[/.-]} in
        gzip | bzip2 | xz | z )
            _mimetype=${_mimetype##*[/.-]}
            _mimetype=${_mimetype//ip}
            _basemimetype=$(file -zLb --mime-type "$1")
            ;;
        stream )
            _mimetype=($(file -Lb "$1"))
            [ "${_mimetype[1]}" = "compressed" ] &&
                _basemimetype=$(file -b --mime-type - < <(
                        ${_mimetype,,} -d <"$1")) ||
                _basemimetype=${_mimetype,,}
            _mimetype=${_mimetype,,}
            ;;
        executable )  _mimetype='' _basemimetype='' ;;
        dosexec )     _mimetype='' _basemimetype='exe' ;;
        shellscript ) _mimetype='' _basemimetype='sh' ;;
        * )
            _basemimetype=$_mimetype
            _mimetype=''
            ;;
    esac
    while read -a _line ;do
        if [ "$_line" == "$_basemimetype" ] ;then
            [ "$_line[1]" ] &&
                _basemimetype=${_line[1]} ||
                _basemimetype=${_basemimetype##*[/.-]}
            break
        fi
        done </etc/mime.types
    case ${_basemimetype##*[/.-]} in
        executable ) _basemimetype='' ;;
        shellscript ) _basemimetype='sh' ;;
        dosexec ) _basemimetype='exe' ;;
        * ) ;;
    esac
    [ "$_mimetype" ] && [ "$_basemimetype" != "$_mimetype" ] &&
      printf ${2+-v} $2 "%s.%s" ${_basemimetype##*[/.-]} ${_mimetype##*[/.-]} ||
      printf ${2+-v} $2 "%s" ${_basemimetype##*[/.-]}
}

这个函数可以设置一个以后可以使用的 Bash 变量:

(这是来自@Petesh 正确答案的启发):

filename=$(basename "$fullfile")
filename="${filename%.*}"
file2ext "$fullfile" extension

echo "$fullfile -> $filename . $extension"
于 2013-07-07T15:47:25.763 回答
9
$ F = "text file.test.txt"  
$ echo ${F/*./}  
txt  

这适合文件名中的多个点和空格,但是如果没有扩展名,它会返回文件名本身。不过很容易检查;只需测试文件名和扩展名是否相同。

自然,此方法不适用于 .tar.gz 文件。然而,这可以通过两步过程来处理。如果扩展名是 gz 则再次检查是否还有 tar 扩展名。

于 2011-04-10T13:58:28.480 回答
9

好的,如果我理解正确,这里的问题是如何获取具有多个扩展名的文件的名称和完整扩展名,例如stuff.tar.gz.

这对我有用:

fullfile="stuff.tar.gz"
fileExt=${fullfile#*.}
fileName=${fullfile%*.$fileExt}

这将为您stuff提供文件名和.tar.gz扩展名。它适用于任意数量的扩展,包括 0。希望这对遇到相同问题的人有所帮助 =)

于 2011-12-09T19:27:02.373 回答
8

只需使用${parameter%word}

在你的情况下:

${FILE%.*}

如果你想测试它,下面的所有工作,只需删除扩展:

FILE=abc.xyz; echo ${FILE%.*};
FILE=123.abc.xyz; echo ${FILE%.*};
FILE=abc; echo ${FILE%.*};
于 2010-07-12T12:44:04.007 回答
7

我使用以下脚本

$ echo "foo.tar.gz"|rev|cut -d"." -f3-|rev
foo
于 2014-03-22T12:56:10.163 回答
7

如何在fish中提取文件名和扩展名:

function split-filename-extension --description "Prints the filename and extension"
  for file in $argv
    if test -f $file
      set --local extension (echo $file | awk -F. '{print $NF}')
      set --local filename (basename $file .$extension)
      echo "$filename $extension"
    else
      echo "$file is not a valid file"
    end
  end
end

警告:在最后一个点上拆分,这适用于其中包含点的文件名,但不适用于包含点的扩展名。请参见下面的示例。

用法:

$ split-filename-extension foo-0.4.2.zip bar.tar.gz
foo-0.4.2 zip  # Looks good!
bar.tar gz  # Careful, you probably want .tar.gz as the extension.

可能有更好的方法来做到这一点。随时编辑我的答案以改进它。


如果您将处理一组有限的扩展并且您知道所有这些扩展,请尝试以下操作:

switch $file
  case *.tar
    echo (basename $file .tar) tar
  case *.tar.bz2
    echo (basename $file .tar.bz2) tar.bz2
  case *.tar.gz
    echo (basename $file .tar.gz) tar.gz
  # and so on
end

这没有作为第一个示例的警告,但是您确实必须处理每种情况,因此根据您可以预期的扩展数量,它可能会更加乏味。

于 2014-03-30T21:41:03.273 回答
6

这是AWK的代码。它可以做得更简单。但是我不擅长AWK。

filename$ ls
abc.a.txt  a.b.c.txt  pp-kk.txt
filename$ find . -type f | awk -F/ '{print $2}' | rev | awk -F"." '{$1="";print}' | rev | awk 'gsub(" ",".") ,sub(".$", "")'
abc.a
a.b.c
pp-kk
filename$ find . -type f | awk -F/ '{print $2}' | awk -F"." '{print $NF}'
txt
txt
txt
于 2011-11-21T10:35:44.203 回答
6

这是唯一对我有用的:

path='folder/other_folder/file.js'

base=${path##*/}
echo ${base%.*}

>> file

这也可以用于字符串插值,但不幸的是你必须base事先设置。

于 2019-06-08T07:42:26.510 回答
5

很大程度上基于@mklement0 的优秀,充满了随机,有用的bashisms - 以及对这个/其他问题/“那个该死的互联网”的其他答案......我把它全部包装了一点,稍微更容易理解,我(或你的)的可重用函数负责(.bash_profile我认为)应该是一个更健壮的版本dirname//你有什么..basename

function path { SAVEIFS=$IFS; IFS=""   # stash IFS for safe-keeping, etc.
    [[ $# != 2 ]] && echo "usage: path <path> <dir|name|fullname|ext>" && return    # demand 2 arguments
    [[ $1 =~ ^(.*/)?(.+)?$ ]] && {     # regex parse the path
        dir=${BASH_REMATCH[1]}
        file=${BASH_REMATCH[2]}
        ext=$([[ $file = *.* ]] && printf %s ${file##*.} || printf '')
        # edge cases for extensionless files and files like ".nesh_profile.coffee"
        [[ $file == $ext ]] && fnr=$file && ext='' || fnr=${file:0:$((${#file}-${#ext}))}
        case "$2" in
             dir) echo      "${dir%/*}"; ;;
            name) echo      "${fnr%.*}"; ;;
        fullname) echo "${fnr%.*}.$ext"; ;;
             ext) echo           "$ext"; ;;
        esac
    }
    IFS=$SAVEIFS
}     

使用示例...

SOMEPATH=/path/to.some/.random\ file.gzip
path $SOMEPATH dir        # /path/to.some
path $SOMEPATH name       # .random file
path $SOMEPATH ext        # gzip
path $SOMEPATH fullname   # .random file.gzip                     
path gobbledygook         # usage: -bash <path> <dir|name|fullname|ext>
于 2013-08-27T02:18:45.857 回答
5

Petesh答案构建,如果只需要文件名,则路径和扩展名都可以在一行中剥离,

filename=$(basename ${fullname%.*})
于 2015-12-04T16:26:45.190 回答
4

一个简单的答案:

要扩展POSIX 变量answer,请注意您可以做更多有趣的模式。因此,对于此处详述的案例,您可以简单地执行以下操作:

tar -zxvf $1
cd ${1%.tar.*}

这将切断 .tar 的最后一次出现。<某事>

更一般地说,如果您想删除最后一次出现的 . <某事><something-else>然后

${1.*.*}

应该可以正常工作。

上述答案的链接似乎已失效。这是对您可以直接在 Bash 中进行的一系列字符串操作的很好解释,来自 TLDP

于 2014-06-09T21:18:42.690 回答
3

如果您还想允许扩展名,这是我能想到的最短的:

echo 'hello.txt' | sed -r 's/.+\.(.+)|.*/\1/' # EXTENSION
echo 'hello.txt' | sed -r 's/(.+)\..+|(.*)/\1\2/' # FILENAME

第一行解释:它匹配 PATH.EXT 或 ANYTHING 并将其替换为 EXT。如果 ANYTHING 匹配,则不会捕获 ext 组。

于 2017-09-16T04:41:23.643 回答
3

恕我直言,已经给出了最佳解决方案(使用 shell 参数扩展),并且是目前评价最高的解决方案。

然而,我添加了这个只使用哑命令的命令,它效率不高,而且任何人都不应该使用它:

FILENAME=$(echo $FILE | cut -d . -f 1-$(printf $FILE | tr . '\n' | wc -l))
EXTENSION=$(echo $FILE | tr . '\n' | tail -1)

添加只是为了好玩:-)

于 2018-12-11T02:16:21.367 回答
3

以前没有答案使用 bash 正则表达式
这是一个纯 bash ERE 解决方案,它将路径拆分为:

  • 目录路径/,存在时带有尾随丢弃尾随的正则表达式长得多,以至于我没有发布它
    /
  • 文件名,不包括(最后一个)点扩展名
  • (最后一个)点扩展,其前导.

该代码旨在处理所有可能的情况,欢迎您尝试。

#!/bin/bash

for path; do

####### the relevant part ######

[[ $path =~ ^(\.{1,2}|.*/\.{0,2})$|^(.*/)([^/]+)(\.[^/]*)$|^(.*/)(.+)$|^(.+)(\..*)$|^(.+)$ ]]

dirpath="${BASH_REMATCH[1]}${BASH_REMATCH[2]}${BASH_REMATCH[5]}"
filename="${BASH_REMATCH[3]}${BASH_REMATCH[6]}${BASH_REMATCH[7]}${BASH_REMATCH[9]}"
filext="${BASH_REMATCH[4]}${BASH_REMATCH[8]}"

# dirpath should be non-null
[[ $dirpath ]] || dirpath='.'

################################

printf '%s=%q\n' \
    path     "$path" \
    dirpath  "$dirpath" \
    filename "$filename" \
    filext   "$filext"

done

它是如何工作的?

基本上,它确保只有一个子表达式(|在正则表达式中分隔)能够捕获输入。多亏了这一点,您可以毫无顾虑地连接所有相同类型的捕获组(例如,与目录路径相关的捕获组),BASH_REMATCH因为最多一个将是非空的。

以下是一组扩展但并不详尽的示例的结果:
+--------------------------------------------------------+
| input             dirpath        filename       filext |
+--------------------------------------------------------+
''                  .              ''             ''
.                   .              ''             ''
..                  ..             ''             ''
...                 .              ..             .
.file               .              .file          ''
.file.              .              .file          .
.file..             .              .file.         .
.file.Z             .              .file          .Z
.file.sh.Z          .              .file.sh       .Z
file                .              file           ''
file.               .              file           .
file..              .              file.          .
file.Z              .              file           .Z
file.sh.Z           .              file.sh        .Z
dir/                dir/           ''             ''
dir/.               dir/.          ''             ''
dir/...             dir/           ..             .
dir/.file           dir/           .file          ''
dir/.file.          dir/           .file          .
dir/.file..         dir/           .file.         .
dir/.file.Z         dir/           .file          .Z
dir/.file.x.Z       dir/           .file.x        .Z
dir/file            dir/           file           ''
dir/file.           dir/           file           .
dir/file..          dir/           file.          .
dir/file.Z          dir/           file           .Z
dir/file.x.Z        dir/           file.x         .Z
dir./.              dir./.         ''             ''
dir./...            dir./          ..             .
dir./.file          dir./          .file          ''
dir./.file.         dir./          .file          .
dir./.file..        dir./          .file.         .
dir./.file.Z        dir./          .file          .Z
dir./.file.sh.Z     dir./          .file.sh       .Z
dir./file           dir./          file           ''
dir./file.          dir./          file           .
dir./file..         dir./          file.          .
dir./file.Z         dir./          file           .Z
dir./file.x.Z       dir./          file.x         .Z
dir//               dir//          ''             ''
dir//.              dir//.         ''             ''
dir//...            dir//          ..             .
dir//.file          dir//          .file          ''
dir//.file.         dir//          .file          .
dir//.file..        dir//          .file.         .
dir//.file.Z        dir//          .file          .Z
dir//.file.x.Z      dir//          .file.x        .Z
dir//file           dir//          file           ''
dir//file.          dir//          file           .
dir//file..         dir//          file.          .
dir//file.Z         dir//          file           .Z
dir//file.x.Z       dir//          file.x         .Z
dir.//.             dir.//.        ''             ''
dir.//...           dir.//         ..             .
dir.//.file         dir.//         .file          ''
dir.//.file.        dir.//         .file          .
dir.//.file..       dir.//         .file.         .
dir.//.file.Z       dir.//         .file          .Z
dir.//.file.x.Z     dir.//         .file.x        .Z
dir.//file          dir.//         file           ''
dir.//file.         dir.//         file           .
dir.//file..        dir.//         file.          .
dir.//file.Z        dir.//         file           .Z
dir.//file.x.Z      dir.//         file.x         .Z
/                   /              ''             ''
/.                  /.             ''             ''
/..                 /..            ''             ''
/...                /              ..             .
/.file              /              .file          ''
/.file.             /              .file          .
/.file..            /              .file.         .
/.file.Z            /              .file          .Z
/.file.sh.Z         /              .file.sh       .Z
/file               /              file           ''
/file.              /              file           .
/file..             /              file.          .
/file.Z             /              file           .Z
/file.sh.Z          /              file.sh        .Z
/dir/               /dir/          ''             ''
/dir/.              /dir/.         ''             ''
/dir/...            /dir/          ..             .
/dir/.file          /dir/          .file          ''
/dir/.file.         /dir/          .file          .
/dir/.file..        /dir/          .file.         .
/dir/.file.Z        /dir/          .file          .Z
/dir/.file.x.Z      /dir/          .file.x        .Z
/dir/file           /dir/          file           ''
/dir/file.          /dir/          file           .
/dir/file..         /dir/          file.          .
/dir/file.Z         /dir/          file           .Z
/dir/file.x.Z       /dir/          file.x         .Z
/dir./.             /dir./.        ''             ''
/dir./...           /dir./         ..             .
/dir./.file         /dir./         .file          ''
/dir./.file.        /dir./         .file          .
/dir./.file..       /dir./         .file.         .
/dir./.file.Z       /dir./         .file          .Z
/dir./.file.sh.Z    /dir./         .file.sh       .Z
/dir./file          /dir./         file           ''
/dir./file.         /dir./         file           .
/dir./file..        /dir./         file.          .
/dir./file.Z        /dir./         file           .Z
/dir./file.x.Z      /dir./         file.x         .Z
/dir//              /dir//         ''             ''
/dir//.             /dir//.        ''             ''
/dir//...           /dir//         ..             .
/dir//.file         /dir//         .file          ''
/dir//.file.        /dir//         .file          .
/dir//.file..       /dir//         .file.         .
/dir//.file.Z       /dir//         .file          .Z
/dir//.file.x.Z     /dir//         .file.x        .Z
/dir//file          /dir//         file           ''
/dir//file.         /dir//         file           .
/dir//file..        /dir//         file.          .
/dir//file.Z        /dir//         file           .Z
/dir//file.x.Z      /dir//         file.x         .Z
/dir.//.            /dir.//.       ''             ''
/dir.//...          /dir.//        ..             .
/dir.//.file        /dir.//        .file          ''
/dir.//.file.       /dir.//        .file          .
/dir.//.file..      /dir.//        .file.         .
/dir.//.file.Z      /dir.//        .file          .Z
/dir.//.file.x.Z    /dir.//        .file.x        .Z
/dir.//file         /dir.//        file           ''
/dir.//file.        /dir.//        file           .
/dir.//file..       /dir.//        file.          .
/dir.//file.Z       /dir.//        file           .Z
/dir.//file.x.Z     /dir.//        file.x         .Z
//                  //             ''             ''
//.                 //.            ''             ''
//..                //..           ''             ''
//...               //             ..             .
//.file             //             .file          ''
//.file.            //             .file          .
//.file..           //             .file.         .
//.file.Z           //             .file          .Z
//.file.sh.Z        //             .file.sh       .Z
//file              //             file           ''
//file.             //             file           .
//file..            //             file.          .
//file.Z            //             file           .Z
//file.sh.Z         //             file.sh        .Z
//dir/              //dir/         ''             ''
//dir/.             //dir/.        ''             ''
//dir/...           //dir/         ..             .
//dir/.file         //dir/         .file          ''
//dir/.file.        //dir/         .file          .
//dir/.file..       //dir/         .file.         .
//dir/.file.Z       //dir/         .file          .Z
//dir/.file.x.Z     //dir/         .file.x        .Z
//dir/file          //dir/         file           ''
//dir/file.         //dir/         file           .
//dir/file..        //dir/         file.          .
//dir/file.Z        //dir/         file           .Z
//dir/file.x.Z      //dir/         file.x         .Z
//dir./.            //dir./.       ''             ''
//dir./...          //dir./        ..             .
//dir./.file        //dir./        .file          ''
//dir./.file.       //dir./        .file          .
//dir./.file..      //dir./        .file.         .
//dir./.file.Z      //dir./        .file          .Z
//dir./.file.sh.Z   //dir./        .file.sh       .Z
//dir./file         //dir./        file           ''
//dir./file.        //dir./        file           .
//dir./file..       //dir./        file.          .
//dir./file.Z       //dir./        file           .Z
//dir./file.x.Z     //dir./        file.x         .Z
//dir//             //dir//        ''             ''
//dir//.            //dir//.       ''             ''
//dir//...          //dir//        ..             .
//dir//.file        //dir//        .file          ''
//dir//.file.       //dir//        .file          .
//dir//.file..      //dir//        .file.         .
//dir//.file.Z      //dir//        .file          .Z
//dir//.file.x.Z    //dir//        .file.x        .Z
//dir//file         //dir//        file           ''
//dir//file.        //dir//        file           .
//dir//file..       //dir//        file.          .
//dir//file.Z       //dir//        file           .Z
//dir//file.x.Z     //dir//        file.x         .Z
//dir.//.           //dir.//.      ''             ''
//dir.//...         //dir.//       ..             .
//dir.//.file       //dir.//       .file          ''
//dir.//.file.      //dir.//       .file          .
//dir.//.file..     //dir.//       .file.         .
//dir.//.file.Z     //dir.//       .file          .Z
//dir.//.file.x.Z   //dir.//       .file.x        .Z
//dir.//file        //dir.//       file           ''
//dir.//file.       //dir.//       file           .
//dir.//file..      //dir.//       file.          .
//dir.//file.Z      //dir.//       file           .Z
//dir.//file.x.Z    //dir.//       file.x         .Z

如您所见,该行为与basename和不同dirname。例如basename dir/输出dir,而正则表达式将为您提供一个空文件名。.和相同..,它们被视为目录,而不是文件名。

我用 256 个字符的 10000 条路径对其进行计时,大约需要 1 秒,而等效的 POSIX shell 解决方案要慢 2 倍,而基于野生分叉(for循环内的外部调用)的解决方案至少要慢 60 倍。

备注:没有必要测试包含\n或其他臭名昭著字符的路径,因为所有字符都由 bash 的正则表达式引擎以相同的方式处理。唯一能够打破当前逻辑的字符是/and ,以当前意想不到的方式.混合或相乘。当我第一次发布我的答案时,我发现了一些我必须修复的边界案例;我不能说正则表达式是 100% 防弹的,但它现在应该非常健壮。


顺便说一句,这是产生相同输出的纯 POSIX shell 解决方案:

#!/bin/sh

for path; do

####### the relevant part ######

basename=${path##*/}

case $basename in
. | ..)
    dirpath="$path"
    filename=''
    filext=''
    basename=''
    ;;
*)
    dirpath=${path%"$basename"}
    filename=${basename#.}
    filename="${basename%"$filename"}${filename%.*}"
    filext=${basename#"$filename"}
esac

# dirpath should be non-null
[ -z "$dirpath" ] && dirpath='.'

################################

printf '%s=%s\n' \
    path     "$filepath" \
    dirpath  "$dirpath" \
    filename "$filename" \
    filext   "$filext"

done

后记:有几点可能有人不同意上述代码给出的结果:

  • dotfiles的特殊情况:原因是dotfiles 一个 UNIX 概念。

  • .and的特殊情况..:恕我直言,将它们视为目录似乎很明显,但大多数库都没有,并强制用户对结果进行后处理。

  • 不支持双扩展:这是因为您需要一个完整的数据库来存储所有有效的双扩展,最重要的是,因为文件扩展在 UNIX 中没有任何意义;例如,您可以调用 tar 存档my_tarred_files,这完全没问题,您可以tar xf my_tarred_files毫无问题地使用。

于 2022-02-04T02:13:20.507 回答
2

这是我在编写 Bash 脚本以在名称与大小写冲突时使名称唯一时用于查找文件的名称和扩展名的算法。

#! /bin/bash 

#
# Finds 
# -- name and extension pairs
# -- null extension when there isn't an extension.
# -- Finds name of a hidden file without an extension
# 

declare -a fileNames=(
  '.Montreal' 
  '.Rome.txt' 
  'Loundon.txt' 
  'Paris' 
  'San Diego.txt'
  'San Francisco' 
  )

echo "Script ${0} finding name and extension pairs."
echo 

for theFileName in "${fileNames[@]}"
do
     echo "theFileName=${theFileName}"  

     # Get the proposed name by chopping off the extension
     name="${theFileName%.*}"

     # get extension.  Set to null when there isn't an extension
     # Thanks to mklement0 in a comment above.
     extension=$([[ "$theFileName" == *.* ]] && echo ".${theFileName##*.}" || echo '')

     # a hidden file without extenson?
     if [ "${theFileName}" = "${extension}" ] ; then
         # hidden file without extension.  Fixup.
         name=${theFileName}
         extension=""
     fi

     echo "  name=${name}"
     echo "  extension=${extension}"
done 

试运行。

$ config/Name\&Extension.bash 
Script config/Name&Extension.bash finding name and extension pairs.

theFileName=.Montreal
  name=.Montreal
  extension=
theFileName=.Rome.txt
  name=.Rome
  extension=.txt
theFileName=Loundon.txt
  name=Loundon
  extension=.txt
theFileName=Paris
  name=Paris
  extension=
theFileName=San Diego.txt
  name=San Diego
  extension=.txt
theFileName=San Francisco
  name=San Francisco
  extension=
$ 

仅供参考:完整的音译程序和更多测试用例可以在这里找到: https ://www.dropbox.com/s/4c6m0f2e28a1vxf/avoid-clashes-code.zip?dl=0

于 2014-10-21T21:47:43.170 回答
1

使用示例文件/Users/Jonathan/Scripts/bash/MyScript.sh,此代码:

MY_EXT=".${0##*.}"
ME=$(/usr/bin/basename "${0}" "${MY_EXT}")

将导致${ME}存在MyScript${MY_EXT}存在.sh


脚本:

#!/bin/bash
set -e

MY_EXT=".${0##*.}"
ME=$(/usr/bin/basename "${0}" "${MY_EXT}")

echo "${ME} - ${MY_EXT}"

一些测试:

$ ./MyScript.sh 
MyScript - .sh

$ bash MyScript.sh
MyScript - .sh

$ /Users/Jonathan/Scripts/bash/MyScript.sh
MyScript - .sh

$ bash /Users/Jonathan/Scripts/bash/MyScript.sh
MyScript - .sh
于 2012-05-19T18:59:03.813 回答
1

从上面的答案来看,模仿 Python 的最短单线器

file, ext = os.path.splitext(path)

假设您的文件确实有扩展名,是

EXT="${PATH##*.}"; FILE=$(basename "$PATH" .$EXT)
于 2014-01-03T11:14:33.260 回答
0

也许可以选择tar这样做;你检查过男人吗?否则,您可以使用Bash 字符串扩展

test="mpc-1.0.1.tar.gz"
noExt="${test/.tar.gz/}" # Remove the string '.tar.gz'
echo $noExt
于 2013-02-05T08:51:39.993 回答
0

为了使 dir 更有用(在没有路径的本地文件被指定为输入的情况下)我做了以下事情:

# Substring from 0 thru pos of filename
dir="${fullpath:0:${#fullpath} - ${#filename}}"
if [[ -z "$dir" ]]; then
    dir="./"
fi

这使您可以做一些有用的事情,例如将后缀添加到输入文件基本名称:

outfile=${dir}${base}_suffix.${ext}

testcase: foo.bar
dir: "./"
base: "foo"
ext: "bar"
outfile: "./foo_suffix.bar"

testcase: /home/me/foo.bar
dir: "/home/me/"
base: "foo"
ext: "bar"
outfile: "/home/me/foo_suffix.bar"
于 2013-08-08T23:59:55.920 回答
0

您可以使用

sed 's/^/./' | rev | cut -d. -f2- | rev | cut -c2-

获取文件名和

sed 's/^/./' | rev | cut -d. -f1  | rev

获得扩展。

测试用例:

echo "filename.gz"     | sed 's/^/./' | rev | cut -d. -f2- | rev | cut -c2-
echo "filename.gz"     | sed 's/^/./' | rev | cut -d. -f1  | rev
echo "filename"        | sed 's/^/./' | rev | cut -d. -f2- | rev | cut -c2-
echo "filename"        | sed 's/^/./' | rev | cut -d. -f1  | rev
echo "filename.tar.gz" | sed 's/^/./' | rev | cut -d. -f2- | rev | cut -c2-
echo "filename.tar.gz" | sed 's/^/./' | rev | cut -d. -f1  | rev
于 2014-05-22T20:24:16.787 回答
0

这是一个sed提取各种形式的路径组件并且可以处理大多数边缘情况的解决方案:

## Enter the input path and field separator character, for example:
## (separatorChar must not be present in inputPath)

inputPath="/path/to/Foo.bar"
separatorChar=":"

## sed extracts the path components and assigns them to output variables

oldIFS="$IFS"
IFS="$separatorChar"
read dirPathWithSlash dirPath fileNameWithExt fileName fileExtWithDot fileExt <<<"$(sed -En '
s/^[[:space:]]+//
s/[[:space:]]+$//
t l1
:l1
s/^([^/]|$)//
t
s/[/]+$//
t l2
:l2
s/^$/filesystem\/\
filesystem/p
t
h
s/^(.*)([/])([^/]+)$/\1\2\
\1\
\3/p
g
t l3
:l3
s/^.*[/]([^/]+)([.])([a-zA-Z0-9]+)$/\1\
\2\3\
\3/p
t
s/^.*[/](.+)$/\1/p
' <<<"$inputPath" | tr "\n" "$separatorChar")"
IFS="$oldIFS"

## Results (all use separatorChar=":")

## inputPath        = /path/to/Foo.bar
## dirPathWithSlash = /path/to/
## dirPath          = /path/to 
## fileNameWithExt  = Foo.bar
## fileName         = Foo
## fileExtWithDot   = .bar
## fileExt          = bar

## inputPath        = /path/to/Foobar
## dirPathWithSlash = /path/to/
## dirPath          = /path/to 
## fileNameWithExt  = Foobar
## fileName         = Foobar
## fileExtWithDot   =
## fileExt          =

## inputPath        = /path/to/...bar
## dirPathWithSlash = /path/to/
## dirPath          = /path/to 
## fileNameWithExt  = ...bar
## fileName         = ..
## fileExtWithDot   = .bar
## fileExt          = bar

## inputPath        = /path/to/..bar
## dirPathWithSlash = /path/to/
## dirPath          = /path/to 
## fileNameWithExt  = ..bar
## fileName         = .
## fileExtWithDot   = .bar
## fileExt          = bar

## inputPath        = /path/to/.bar
## dirPathWithSlash = /path/to/
## dirPath          = /path/to 
## fileNameWithExt  = .bar
## fileName         = .bar
## fileExtWithDot   = 
## fileExt          = 

## inputPath        = /path/to/...
## dirPathWithSlash = /path/to/
## dirPath          = /path/to 
## fileNameWithExt  = ...
## fileName         = ...
## fileExtWithDot   =
## fileExt          =

## inputPath        = /path/to/Foo.
## dirPathWithSlash = /path/to/
## dirPath          = /path/to 
## fileNameWithExt  = Foo.
## fileName         = Foo.
## fileExtWithDot   =
## fileExt          =

## inputPath        = / (the root directory)
## dirPathWithSlash = filesystem/
## dirPath          = filesystem
## fileNameWithExt  =
## fileName         =
## fileExtWithDot   =
## fileExt          =

## inputPath        =  (invalid because empty)
## dirPathWithSlash =
## dirPath          =
## fileNameWithExt  =
## fileName         =
## fileExtWithDot   =
## fileExt          =

## inputPath        = Foo/bar (invalid because doesn't start with a forward slash)
## dirPathWithSlash =
## dirPath          =
## fileNameWithExt  =
## fileName         =
## fileExtWithDot   =
## fileExt          =

以下是它的工作原理:

sed解析输入路径并在单独的行上按顺序打印以下路径组件:

  • 带有尾部斜杠字符的目录路径
  • 没有尾部斜杠字符的目录路径
  • 带扩展名的文件名
  • 不带扩展名的文件名
  • 带有前导点字符的文件扩展名
  • 没有前导点字符的文件扩展名

trsed输出转换为上述路径组件的分隔符分隔字符串。

read使用分隔符作为字段分隔符 ( IFS="$separatorChar") 并将每个路径组件分配给其各自的变量。

以下是sed构造的工作原理:

  • s/^[[:space:]]+//s/[[:space:]]+$//去除任何前导和/或尾随空白字符
  • t l1并为下一个函数:l1刷新函数ts
  • s/^([^/]|$)//t测试无效的输入路径(不以正斜杠开头的路径),在这种情况下,它将所有输出行留空并退出sed命令
  • s/[/]+$//去除任何尾随斜杠
  • t l2并为下一个函数:l2刷新函数ts
  • s/^$/filesystem\/\\[newline]filesystem/pt测试输入路径由根目录/组成的特殊情况,在这种情况下,它为dirPathWithSlashdirPath输出行打印filesystem/filesystem,将所有其他输出行留空,并退出sed命令
  • h将输入路径保存在保持空间中
  • s/^(.*)([/])([^/]+)$/\1\2\\[newline]\1\\[newline]\3/p打印dirPathWithSlashdirPathfileNameWithExt输出行
  • g从保持空间中检索输入路径
  • t l3并为下一个函数:l3刷新函数ts
  • s/^.*\[/]([^/]+)([.])([a-zA-Z0-9]+)$/\1\\[newline]\2\3\\[newline]\3/p并在存在文件扩展名的情况下t打印fileNamefileExtWithDotfileExtsed输出行(假设仅由字母数字字符组成),然后退出命令
  • s/^.*\[/](.+)$/\1/p在文件扩展名不存在的情况下打印fileName但不打印fileExtWithDotfileExtsed输出行,然后退出命令。
于 2016-10-13T05:56:44.050 回答
-1

您还可以使用for循环并tr从路径中提取文件名...

for x in `echo $path | tr "/" " "`; do filename=$x; done

用空格tr替换路径中的所有“ / ”定界符,从而制作一个字符串列表,然后for循环扫描它们,将最后一个留在filename变量中。

于 2011-07-01T08:20:22.673 回答
-2

一个简单的 bash one 班轮。我用它从pwd中的所有文件中删除rst扩展名

for each in `ls -1 *.rst`
do
     a=$(echo $each | wc -c)
     echo $each | cut -c -$(( $a-5 )) >> blognames
done

它能做什么 ?

1)ls -1 *.rst将在新行中列出标准输出上的所有文件(尝试)。

2)echo $each | wc -c计算每个文件名中的字符数。

3)echo $each | cut -c -$(( $a-5 ))最多选择最后 4 个字符,即.rst.

于 2014-07-30T08:11:12.293 回答