Home  >  Article  >  Backend Development  >  Easy way to get filenames and directory names using Bash Shell

Easy way to get filenames and directory names using Bash Shell

高洛峰
高洛峰Original
2017-01-09 13:28:051825browse

前言
还是今天再写一个自动化打包脚本,用到了从路径名中获取最后的文件名。这里记录一下实现过程。当然,最后我也会给出官方的做法。(ps:很囧,实现完了才发现原来Bash Shell有现成的函数)

获取文件名
假设给定的路径名为:

/tmp/csdn/zhengyi/test/zhengyi.txt

 awk解法

用“/”做分隔符,然后打印出最后的那一部分。实现代码如下

resFile=`echo /tmp/csdn/zhengyi/test/adb.log | awk -F "/" '{print $NF}'`

   

官方解法(basename)
Bash Shell本身提供了basename命令,可以直接获取路径名最后的文件名,实现代码如下:

resFile=`basename /tmp/csdn/zhengyi/test/adb.log`

获取目录名

官方解法(dirname)
Bash Shell本身提供了dirname命令,特别方便,可以直接获取路径对应的目录名,实现代码如下:

dirPath=`dirname /tmp/csdn/zhengyi/test/adb.log`

awk解法

可以灵活的使用分隔符,混合正则表达式:

dirPath=`echo /tmp/csdn/zhengyi/test/adb.log | awk -F '/[^/]*$' '{print $1}'`

awk+for循环的方法:

echo /tmp/csdn/zhengyi/test/adb.log | awk &#39;BEGIN{res=""; FS="/";}{ for(i=2;i<=NF-1;i++) res=(res"/"$i);} END{print res}&#39;

  

更多使用Bash Shell获取文件名和目录名的简单方法相关文章请关注PHP中文网!


Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn