使用 awk 正则表达式捕获插入符 (^)
我有这种格式的输出:
/ignore-this/^/../I/want/this@ignore-this
我正在尝试使用 awk 正则表达式来捕获以下内容:
../I/want/this
这不会特别困难,除了我无法弄清楚如何正确转义 ^
所以它不是解释为换行或不换行。下面是我到目前为止所拥有的,它几乎可以工作,除了打印出来:
/ignore-this/^/../I/want/this
这是代码:
#!/bin/awk -f
{
if (match($0, "\^.*@")){
print substr($0, RSTART, RLENGTH-1);
}
}
I have output with this format:
/ignore-this/^/../I/want/this@ignore-this
I am trying to use an awk regex to capture the following:
../I/want/this
This wouldn't be particularly hard except that I cannot figure out how to properly escape the ^
so it is not interpretted as an new line or a not. Below is what I have so far, it almost works except it prints out:
/ignore-this/^/../I/want/this
Here is the code:
#!/bin/awk -f
{
if (match($0, "\^.*@")){
print substr($0, RSTART, RLENGTH-1);
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
另一种可能性,使用 gawk:
Another possibility, using gawk:
输出:
这将输入流拆分为所有“^”。然后它获取最后一个字段并将其拆分为“@”并打印字符串的前半部分。
编辑:
或使用:
HTH Chris
output:
This splits the input stream on all "^". Then it takes the last field and splits it on "@" and prints the first half of the string.
EDIT:
Or use:
HTH Chris
在这种情况下应该有效
should work in this case
说到
awk
regex
和插入符"^"
,乍一看这可能看起来很奇怪,因为为什么后一个仅对第一个加倍有效正则表达式:第一个无效,原因很明显:
[...]
^ 缺乏转义>第二个是有效的,因为它实际上代表:
]
、[
或^
此处的顺序实际上很重要:将其写为
/[^[]^] /
相反,所发生的情况是gawk
和mawk
只是默默地失败(或者匹配一些与你的初衷完全不相近的东西) ) 而nawk
只是出错speaking of
awk
regex
with carets"^"
, this may look strange at first glance regarding why the latter one is valid for merely doubling the firstregex
:1st one is invalid for the obvious reason :
^
inside a character class[…]
2nd one is valid cuz it actually stands for :
]
,[
, or^
The order actually matters here : write it as
/[^[]^]/
instead, and what happens is thatgawk
andmawk
simply fail silently (or match something not at all close to what ur original intentions were) whilenawk
simply errors out