如何提取直接目录的名称和文件名?
我有一个文件,其完整路径类似于
/a/b/c/d/filename.txt
如果我执行 basename
在上面,我得到filename.txt
。但这个文件名并不是太独特。
,那就更好了
{immediate directory}_{basename result}
因此,如果我可以将文件名提取为d_filename.txt
,即如何实现此结果?
I have a file whose complete path is like
/a/b/c/d/filename.txt
If I do a basename
on it, I get filename.txt
. But this filename is not too unique.
So, it would be better if I could extract the filename as d_filename.txt
i.e.
{immediate directory}_{basename result}
How can I achieve this result?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
或者
or
该代码将从运行脚本的目录开始递归地搜索层次结构。我以这样的方式对循环进行编码,它将处理您向其抛出的任何文件名;包含空格、换行符等的文件名。
*注意**:循环当前写入不包含此脚本所在目录中的任何文件,它只查看它下面的子目录。这样做是因为这是确保脚本不将自身包含在其处理中的最简单方法。如果由于某种原因您必须包含脚本所在的目录,则可以更改它以适应这种情况。
代码
测试树
输出
This code will recursively search through your hierarchy starting with the directory that you run the script in. I've coded the loop in such a way that it will handle any filename you throw at it; file names with spaces, newlines etc.
*Note**: the loop is currently written to not include any files in the directory that this script resides in, it only looks at subdirs below it. This was done as it was the easiest way to make sure the script does not include itself in its processing. If for some reason you must include the directory the script resides in, it can be changed to accommodate this.
Code
Test tree
Output
不需要调用外部命令
don't need to call external command
举个例子:
限定
file.txt
并避免冲突的唯一可靠方法是将整个路径构建到新文件名中,例如,如果您确定的话,您可以跳过开头的部分内容它对所有文件都是通用的,例如,如果您知道所有文件都位于上面目录
/a
下的某个位置:要在每个文件的基础上实现此目的:
假设您想要递归地执行此操作目录及其子目录:
输出:
以上内容具有高度可移植性,并且基本上可以在任何
sh
变体下的任何 Unix 系统上运行(包括bash
、ksh等)
Take the example:
The only reliable way to qualify
file.txt
and avoid conflicts is to build the entire path into the new filename, e.g.You may be able to skip part of the beginning if you know for sure that it will be common to all files, e.g if you know that all files reside somewhere underneath the directory
/a
above:To achieve this on a per-file basis:
Say you want do do this recursively in a directory and its subdirectories:
Output:
The above is highly portable and will run on essentially any Unix system under any variant of
sh
(inclusingbash
,ksh
etc.)