使用bash参数扩展获取文件的路径 [英] Get path to file using bash parameter expansion

查看:88
本文介绍了使用bash参数扩展获取文件的路径的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给出文件路径,例如:/home/user1/archive.zip

Given a path to a file let say: /home/user1/archive.zip

有人可以告诉我如何在不使用外部二进制文件的情况下删除字符串 archive.zip 吗?

Can someone tell me how can I remove the string archive.zip without using external binaries?

我知道:

${Path2File##*/}

可以给我文件名,但是我需要这个文件夹的路径.

Can give me the file name but I need the folder path for this one.

也欢迎使用通配符理解或解释指南.

A guide to wildcard understanding or an explanation is welcomed as well.

推荐答案

执行

"${Path2File%\/*}"

或使用外部二进制文件

dirname "$Path2File" # Not desirable as you've mentioned already


注释:

  1. 在类型为${parameter%word}的shell参数扩展中,单词扩展为生成模式,就像文件名扩展一样.如果该模式与参数的扩展值的结尾部分匹配,则扩展的结果就是删除了最短匹配模式的参数的值.
  2. 由于/在shell参数扩展中具有特殊含义,因此我们仅对其进行了转义,即\/.目的是匹配文件的基本名称,即 /path/to/example.zip中的/example.zip并将其删除.
  1. In the shell parameter expansion of type ${parameter%word}, the word is expanded to produce a pattern just as in filename expansion. If the pattern matches a trailing portion of the expanded value of parameter, then the result of the expansion is the value of parameter with the shortest matching pattern deleted.
  2. Since the / has special meaning in shell parameter expansion we just escaped it ie \/. The intention is to match the file basename ie /example.zip in /path/to/example.zip and delete it.

参考:

Shell [参数扩展]

这篇关于使用bash参数扩展获取文件的路径的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆