sed 匹配到行尾
我有一个 mysqldump ,其中有几行,例如
CONSTRAINT `FK5E61277CBAE1E8F6` FOREIGN KEY (`action_item_group_id`) REFERENCES `action_item_group` (`id`),
or
CONSTRAINT `FK5E61277CBAE1E8F6` FOREIGN KEY (`action_item_group_id`) REFERENCES `action_item_group` (`id`)
我想在逗号之前添加单词 ON UPDATE CASCADE
,如果存在的话。
在 Vi 中我将其与: /CONSTRAINT\ .*\ 外键\ .*\ 参考文献\ .*\ \(.*\)
如果存在,它会给我精确到逗号的文本,如果不存在,它会给我精确到行尾的文本。
但现在使用 sed
我这样做:
sed -e "s/CONSTRAINT\ .*\ FOREIGN\ KEY\ .*\ REFERENCES\ .*\ \(.*\)/&\ ON\ UPDATE\ CASCADE/"
问题是 &
也匹配逗号,并且我得到像
CONSTRAINT `FK5E61277C881C85E3` FOREIGN KEY (`created_by_employee_id`) REFERENCES `employee` (`id`), ON UPDATE CASCADE
How can I get my ON UPDATE CASCADE
这样的输出> 在逗号之前?
I have a mysqldump with several lines like
CONSTRAINT `FK5E61277CBAE1E8F6` FOREIGN KEY (`action_item_group_id`) REFERENCES `action_item_group` (`id`),
or
CONSTRAINT `FK5E61277CBAE1E8F6` FOREIGN KEY (`action_item_group_id`) REFERENCES `action_item_group` (`id`)
I want to add the words ON UPDATE CASCADE
to each of these, before the comma, if it exists.
In Vi I match it with:/CONSTRAINT\ .*\ FOREIGN\ KEY\ .*\ REFERENCES\ .*\ \(.*\)
which gives me the exact text up to the comma if it exists, or up to the end of the line if it doesn't exist.
But now with sed
I do:
sed -e "s/CONSTRAINT\ .*\ FOREIGN\ KEY\ .*\ REFERENCES\ .*\ \(.*\)/&\ ON\ UPDATE\ CASCADE/"
The problem is &
also matches the comma, and I get output like
CONSTRAINT `FK5E61277C881C85E3` FOREIGN KEY (`created_by_employee_id`) REFERENCES `employee` (`id`), ON UPDATE CASCADE
How can I get my ON UPDATE CASCADE
in before the comma?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您不能将
,
替换为ON UPDATE CASCADE,
还是我误解了这个问题?Can't you just replace the
,
withON UPDATE CASCADE,
or did I misunderstand the question?尝试删除替换表达式中括号前的
\
:\(
表示组的开始,而不是括号。(
仅匹配左括号。Try removing the
\
before the parentheses in the substitute expression:The
\(
means a start of a group, not a parenthesis.(
just matches the left paren.使用
AWK
即可轻松完成:EXAMPLE
NB
匹配中的
CONSTRAINT
可以替换为任何内容你想要匹配的正则表达式。这只是一个简单的例子。但它应该有效。Easy with
AWK
:EXAMPLE
NB
The
CONSTRAINT
in match can be replaced with whatever regex you want to match. This is just an easy example. It should work though.“扩展”正则表达式(带有
sed
的-r
标志)对我来说总是更有意义。然后你会得到\(
意思是一个括号,而(
意思是一个组的开始,这就是你所期望的(根据迭戈·塞维利亚)。这对我有用:结果:
"extended" regular expressions (
-r
flag withsed
) always make more sense to me. Then you get\(
meaning a literal parenthesis and(
meaning start of a group, which is what you seem to be expecting (as per Diego Sevilla). This works for me:result: