我的测试文件有这样的文本:
> cat test.txt
new dummy("test1", random1).foo("bar1");
new dummy("
test2", random2);
new dummy("test3", random3).foo("bar3");
new dummy = dummy(
"test4", random4).foo("bar4");
我正在尝试匹配所有以分号 (;) 结尾并包含文本“dummy(”) 的单行。然后我需要提取出现在 dummy 内双引号中的字符串。我想出了以下命令,但是它只匹配第一条和第三条语句。
> perl -ne 'print if /dummy/ .. /;/' test.txt | grep -oP 'dummy\((.|\n)*,'
dummy("test1",
dummy("test3",
使用 -o 标志,我希望在 dummy 中的双引号之间提取字符串。但这也行不通。你能告诉我如何继续吗?
预期输出是:
test1
test2
test3
test4
下面的一些答案适用于基本文件结构。如果 lines 包含超过 1 个换行符,则代码中断。例如输入换行符较多的文本文件:
new dummy("test1", random1).foo("bar1");
new dummy("
test2", random2);
new dummy("test3", random3).foo("bar3");
new dummy = dummy(
"test4", random4).foo("bar4");
new dummy("test5",
random5).foo("bar5");
new dummy("test6", random6).foo(
"bar6");
new dummy("test7", random7).foo("
bar7");
我提到了以下 SO 链接:
How to give a pattern for new line in grep?
how to grep multiple lines until ; (semicolon)
最佳答案
@TLP 非常接近:
perl -0777 -nE 'say for map {s/^\s+|\s+$//gr} /\bdummy\(\s*"(.+?)"/gs' test.txt
test1
test2
使用
-0777
将文件作为单个字符串插入/\bdummy\(\s*"(.+?)"/gs
查找所有在 "dummy("之后被引用的字符串内容(在引号前有可选的空格)
s
标志允许 .
匹配换行符。map {s/^\s+|\s+$//gr}
去除每个字符串的前导/尾随空格。https://stackoverflow.com/questions/71874725/
相关文章:
nuxt.js - 如何在 Nuxt 3 中间件获取当前域?
c++ - 不能在 std::array 上使用 std::apply
ios - Xcode 构建失败 : Requested but did not find exte
haskell - 为什么不是 (20 >) 。长度 。取 10 === const True
c++ - std::ranges::to 是否允许转换为 std::map?
module - 是否有一种简洁/内联的方式来创建 Set 值而不显式命名它们的类型?