修改使用“find”找到的每个文件
我有一个带有一堆.svg
文件的文件夹。 我想以以下方式修改文件夹中的每个SVG文件:
- 交换
#000000
使用currentColor
- add
class
class 属于基于fileName的值(例如
。
find ./ -name \*.svg -exec sed -i '' -e "s/#000000/currentColor/g;s/<svg/<svg class=\"icon ${name}\"/g" {} +
零件正常。
颜色替换 会非常感谢。
在Mac环境中工作
I have a folder with a bunch of .svg
files.
I want to modify each svg file inside the folder in the following way:
- swap
#000000
withcurrentColor
- add
class
attribute with value based on filename (eg. for file namedicon-super-cool.svg
I wantclass="icon-super-cool"
here's where I've gotten to after hours of googling:
find ./ -name \*.svg -exec sed -i '' -e "s/#000000/currentColor/g;s/<svg/<svg class=\"icon ${name}\"/g" {} +
The colour replace part works fine. When it comes to the class attribute, every single icon get the same class attribute with ${name}
of the 1st file it processes.
Any help and explanation of what I am doing wrong would be much appreciated.
PS. working on a mac environment.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您的尝试存在几个问题:
find
的exec
操作中,找到的文件的名称由{}
表示,而不是${名称}
。{}
,类也会以.svg
结尾,而不是您想要的。{}
,该类也将包含完整的文件路径 (./foo/bar/baz.svg
),而不是您想要的。以下假设您希望类名称为
icon-name
,其中name
是不带.svg
扩展名的文件的基本名称:或者,按照 Charles 的建议,减少 bash 运行的次数:
如果性能确实是一个问题,并且您希望一次处理多个文件(
{} +
而不是{} \;< /code>),事情很困难
sed
因为类替换字符串不是常量(虽然并非不可能,但这将是可怕的)。但 GNUawk
可以做到:第一个块 (
BEGINFILE
) 预处理每个文件名以构建类替换字符串,第二个块执行替换。这应该是最快的(未经测试)。即使使用附带的
find
、sed
、basename
和bash
的默认版本,前两个解决方案也应该可以工作。 macOS。对于最后一个,您绝对需要最新版本的 GNUawk
(请参阅 MacPorts 或 HomeBrew)。There are several issues with your attempt:
exec
action offind
the name of the found file is represented by{}
, not${name}
.{}
the class will end with.svg
, not what you want.{}
the class will contain the full file path (./foo/bar/baz.svg
), not what you want.The following assumes you want the class name to be
icon-name
wherename
is the basename of the file without the.svg
extension:Or, as suggested by Charles, to reduce the number of bash runs:
If performance is really an issue, and you want to process several files at once (
{} +
instead of{} \;
), things are difficult withsed
because the class replacement string is not constant (not impossible, though, but this would be horrible). But GNUawk
can make it:The first block (
BEGINFILE
) preprocesses each file name to build the class replacement string and the second performs the replacements. This should be the fastest of all (not tested).The two first solutions should work even with the default versions of
find
,sed
,basename
andbash
that come with macOS. For the last one you absolutely need a decently recent version of GNUawk
(see MacPorts or HomeBrew).您可以使用一个小脚本(例如,将例如
script.sh
):然后从
查找
以下调用它:You could use a small script (save e.g. as
script.sh
):and then call it from
find
like this: