英文:
How to make wildcard character.* work in shell script
问题
我想循环遍历一些目录中的文件,我尝试了以下代码:
INPUT_PATH=/group/had/muon/cometmgr/MC6/MC6A01/rootracker/oa_g4_proton_00000`printf %03d ${j}`*.rootracker
其中 j
在循环过程中递增,但 INPUT_PATH
的输出只是包含字符 *
的路径,而没有被文件名替换。我错在哪里了?
英文:
I want to loop over files in some directories, I tried
INPUT_PATH=/group/had/muon/cometmgr/MC6/MC6A01/rootracker/oa_g4_proton_00000`printf %03d ${j}`*.rootracker
where j is increasing during the loop, but the output of INPUT_PATH
is just a path including the character *
but not replaced by file name. Where did I do wrong?
答案1
得分: 1
这不起作用是因为变量赋值不会经历文件名扩展(也称为globbing)。根据POSIX,2.9.1中的Simple Commands:
每个变量分配应在分配值之前进行波浪扩展,参数扩展,命令替换,算术扩展和引号去除。
你可以使用eval
来绕过它,但如果你不小心的话,评论区的人可能会批评我建议这样做,因为它可能存在安全风险。
告诉我们更多你想做什么,我们可以建议更好的方法。在那之前,你可以尝试:
INPUT_PATH=/group/had/muon/cometmgr/MC6/MC6A01/rootracker
for j in 0 1 2 3 4 5 6 7 8 9 10; do
frob ${INPUT_PATH}/$(printf %03d $j)*.rootracker
end
这应该能够解决问题。
英文:
This does not work because variable assignments do not undergo filename expansion (aka globbing). According to POSIX, 2.9.1 Simple Commands:
> Each variable assignment shall be expanded for tilde expansion, parameter expansion, command substitution, arithmetic expansion, and quote removal prior to assigning the value.
You could use eval
to get around it, but the SO commentariat will crucify me for suggesting it, since unless you're careful it can be a security risk.
Show us some more of what you want to do and we can suggest a better way. Until then, what about
INPUT_PATH=/group/had/muon/cometmgr/MC6/MC6A01/rootracker
for j in 0 1 2 3 4 5 6 7 8 9 10; do
frob ${INPUT_PATH}/$(printf %03d $j)*.rootracker
done
should do the trick.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论