参数替换 - 删除模式后面的字符串部分
假设我有一个如下所示的路径:
/A/B/C/DIRECTORY/D/E/F
现在,我想要使用参数替换实现的目标是剪切 DIRECTORY 之后的路径部分,无论 DIRECTORY 位于路径中的哪个位置(A、B、C)等仅代表随机目录名称)。
替换后:
/A/B/C/DIRECTORY
这是我到目前为止所尝试过的:
#!/bin/bash
if [[ $# < 1 ]]
then
echo "Usage: $0 DIRECTORY"
fi
CURRENT_DIRECTORY=$(pwd)
DIRECTORY=$1
cd ${CURRENT_DIRECTORY%!(DIRECTORY)/*}
显然,这不起作用。我可以使用 awk 或 sed 来实现这一点,但我很感兴趣是否可以仅使用参数替换。
Let's say I have a path which looks like the following:
/A/B/C/DIRECTORY/D/E/F
Now, what I want to achieve using parameter substitution, is cutting of the part of the path after DIRECTORY, no matter where in the path the DIRECTORY is positioned (A, B, C, etc. just stand for random directory names).
After substitution:
/A/B/C/DIRECTORY
This is what I've tried so far:
#!/bin/bash
if [[ $# < 1 ]]
then
echo "Usage: $0 DIRECTORY"
fi
CURRENT_DIRECTORY=$(pwd)
DIRECTORY=$1
cd ${CURRENT_DIRECTORY%!(DIRECTORY)/*}
Obviously, this doesn't work. I could implement this using awk or sed but I'm interested if it is possible using only parameter substitution.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
也许这可以帮助 -
May be this can help -
当然,这并不完美:
阅读 bash 手册页并搜索“模式替换”。
of course, this isn't perfect:
Read the bash man page and search for "Pattern substitution".
尝试下一个解决方案:
编辑:
更准确的答案是在删除最后一部分后附加您的目录:
Try next solution:
EDIT:
More accurate answer would be appending your directory after removing last part:
感谢 Birei,我找到了这个(不完美但足够好的解决方案:
示例:
Thanks to Birei, I came to this (not perfect but good enough solution:
Example: