简体   繁体   English

在Bash中使用指定路径遍历目录

[英]Iterating over directory with specified path in Bash

pathToBins=$1

bins="${pathToBins}contigs.fa.metabat-bins-*"

for fileName in $bins
do
    echo $fileName

done

My goal is to attach a path to my file name. 我的目标是为文件名添加路径。 I can iterate over a folder and get the file name when I don't attach the path. 不附加路径时,我可以遍历文件夹并获取文件名。 My challenge is when I add the path echo fileName my regular expression no longer works and I get "/home/erikrasmussen/Desktop/Script/realLargeMetaBatBinscontigs.fa.metabat-bins-*" where the regular expression '*' is treated like a string. 我的挑战是,当我添加路径echo fileName时,我的正则表达式不再起作用,并且得到“ /home/erikrasmussen/Desktop/Scr​​ipt/realLargeMetaBatBinscontigs.fa.metabat-bins-*”,其中正则表达式'*'被视为串。 How can I get the path and also the full file name while iterating over a folder of files? 在遍历文件文件夹时如何获取路径以及完整文件名?

Although I don't really know how your files are arranged on your hard drive, a casual glance at "/home/erikrasmussen/Desktop/Script/realLargeMetaBatBinscontigs.fa.metabat-bins-*" suggests that it is missing a / before contigs . 虽然我真的不知道你的文件的排列在硬盘上,随便看一眼"/home/erikrasmussen/Desktop/Script/realLargeMetaBatBinscontigs.fa.metabat-bins-*"顾名思义是之前缺少/ contigs If that is the case, then you should change your definition of bins to: 如果是这种情况,则应将箱的定义更改为:

bins="${pathToBins}/contigs.fa.metabat-bins-*"

However, it is much more robust to use bash arrays instead of relying on filenames to not include whitespace and metacharacters. 但是,使用bash数组而不是依赖文件名不包含空格和元字符要健壮得多。 So I would suggest: 所以我建议:

bins=(${pathToBins}/contigs.fa.metabat-bins-*)
for fileName in "${bins[@]}"
do
    echo "$fileName"
done

Bash normally does not expand a pattern which doesn't match any file, so in that case you will see the original pattern. Bash通常不会展开与任何文件都不匹配的模式,因此在这种情况下,您将看到原始模式。 If you use the array formulation above, you could set the bash option nullglob , which will cause the unmatched pattern to vanish instead, leaving an empty array. 如果使用上面的数组公式,则可以设置bash选项nullglob ,这将导致不匹配的模式消失,从而留下一个空数组。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM