bash 文件名开始匹配
我有一个足够简单的问题,但还没有通过论坛或 bash 获得指导。问题如下:
我想为目录中匹配*.h或*.cpp的每个文件名添加前缀字符串。但是,如果前缀已应用于文件名,请勿再次应用。
为什么以下不起作用尚待弄清楚:
for i in *.{h,cpp}
do
if [[ $i!="$pattern*" ]]
then mv $i $pattern$i
fi
done
I've got a simple enough question, but no guidance yet through the forums or bash. The question is as follows:
I want to add a prefix string to each filename in a directory that matches *.h or *.cpp. HOWEVER, if the prefix has already been applied to the filename, do NOT apply it again.
Why the following doesn't work is something that has yet to be figured out:
for i in *.{h,cpp}
do
if [[ $i!="$pattern*" ]]
then mv $i $pattern$i
fi
done
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
你可以试试这个:
you can try this:
其他人已经展示了有效的替代品比较;我将尝试一下为什么原始版本没有。原始前缀测试有两个问题:比较运算符 (
!=
) 及其操作数之间需要空格,并且星号位于引号中(意味着它按字面匹配,而不是作为通配符) )。修复这些问题,并且(至少在我的测试中)它按预期工作:Others have shown replacements comparisons that work; I'll take a stab at why the original version didn't. There are two problems with the original prefix test: you need spaces between the comparison operator (
!=
) and its operands, and the asterisk was in quotes (meaning it gets matched literally, rather than as a wildcard). Fix these, and (at least in my tests) it works as expected:该脚本将在任何 Posix shell 中运行,而不仅仅是 bash。 (我不确定你的问题是“为什么这不起作用”还是“我如何使其工作”,所以我猜这是第二个。)
This script will run in any Posix shell, not just bash. (I wasn't sure if your question was "why isn't this working" or "how do I make this work" so I guessed it was the second.)
不完全符合您的脚本,但它应该可以工作。如果没有前缀,则检查返回 true(即,如果 $i 删除前缀“prefix”后等于 $i)。
Not exactly conforming to your script, but it should work. The check returns true if there is no prefix (i.e. if $i, with the prefix "prefix" removed, equals $i).