Linux Shell提取文件名称和目录方法

单路径提取

使用${}

 ${}主要用来进行变量的提取和替换等等操作,它可以提取非常多的内容,提取文件路径知识它使用的一个特例

  • #:表示从左边算起第一个
  • %:表示从右边算起第一个
  • ##:表示从左边算起最后一个
  • %%:表示从右边算起最后一个
  • *:表示要删除的内容,对于#和##的情况,它位于指定的字符(例子中的’/‘和’.’)的左边,表于删除指定字符及其左边的内容;对于%和%%的情况,它位于指定的字符(例子中的’/‘和’.’)的右边,表示删除指定字符及其右边的内容。这里的’*'的位置不能互换,即不能把*号放在#或##的右边,反之亦然。

${filePath##*/}

 该命令的作用是去掉变量filePath从左边算起的最后一个’/‘字符及其左边的内容,返回从左边算起的最后一个’/’(不含该字符)的右边的内容。使用例子及结果如下:

[root@localhost tmp]# filePath="/tmp/test.txt"
[root@localhost tmp]# echo ${filePath##*/}
test.txt

${filePath##*.}

 该命令的作用是去掉变量filePath从左边算起的最后一个’.‘字符及其左边的内容,返回从左边算起的最后一个’.’(不含该字符)的右边的内容。使用例子及结果如下:

[root@localhost tmp]# filePath="/tmp/test.txt"
[root@localhost tmp]# echo ${filePath##*.}
txt

${filePath#*.}

 该命令的作用是去掉变量filePath从左边算起的第一个’.‘字符及其左边的内容,返回从左边算起第一个’.’(不含该字符)的右边部分的内容。使用例子及结果如下:

[root@localhost tmp]# filePath="/tmp/test.tar.zip"
[root@localhost tmp]# echo ${filePath#*.}
tar.zip

${filePath%/*}

 该命令的使用是去掉变量filePath从右边算起的第一个’/‘字符及其右边的内容,返回从右边算起的第一个’/’(不含该字符)的左边的内容。使用例子及结果如下:

[root@localhost tmp]# filePath="/tmp/test.txt"
[root@localhost tmp]# echo ${filePath%/*}
/tmp

${filePath%%.*}

 该命令的使用是去掉变量filePath从右边算起的最后一个’.‘字符及其右边的内容,返回从右边算起的最后一个’.’(不含该字符)的左边的内容。

[root@localhost tmp]# filePath="/tmp/test.txt"
[root@localhost tmp]# echo ${filePath%%.*}
/tmp/test

使用basename、dirname

 basename和dirname命令就是专门为做这一件事而已准备的了。

basename

 该命令的作用是从路径中提取出文件名,使用方法为basename NAME [SUFFIX]。

  • 从路径中提出文件名(带后缀):
[root@localhost tmp]# filePath="/tmp/test.txt"
[root@localhost tmp]# echo $(basename $filePath)
test.txt
  • 从上面命令的用法中可以看到,后缀(SUFFIX)是一个可选项。所以,若只想提取出文件名file,而不带有后缀,还可以在变量的后面加上后缀名:
[root@localhost tmp]# filePath="/tmp/test.txt"
[root@localhost tmp]# echo $(basename $filePath .txt)
test

dirname

  该命令的作用是从路径中提取出目录名,使用方法为 dirname NAME

  • 提取test.txt所在目录
[root@localhost tmp]# dirname /tmp/test.txt
/tmp

注:该命令不仅能提取出普通文件所的目录,它能提取出任何文件所在的目录,例如目录所在的目录,如下:

  • 提取目录的目录
[root@localhost tmp]# dirPath=/tmp/testDir/
[root@localhost tmp]# dirname $dirPath
/tmp

提取目录中所有文件名称

get_fileName.sh

#!/bin/bash
folderPath="/root"
files=$(ls $FloderPath)
for filename in $files
do
echo $filename
done

输出

[root@localhost tmp]# bash get_fileName.sh
anaconda-ks.cfg
install.log
install.log.syslog
start_tomcat.sh
Author: HB
Link: http://www.huangbin.fun/Linux-Shell提取文件名称和目录方法.html
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.