尝试打印匹配表达式时使用 sed 的无效引用 \1 [英] Invalid reference \1 using sed when trying to print matching expression

查看:52
本文介绍了尝试打印匹配表达式时使用 sed 的无效引用 \1的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我开始之前,我已经看过这个 问题,但似乎解决方案是他们没有转义正则表达式中的括号.我遇到了同样的错误,但我没有对正则表达式进行分组.我想要做的是在 lastlog 文件中找到所有名称/用户名并仅返回 UN.

Before I start, I already looked at this question, but it seems the solution was that they were not escaping the parentheses in their regex. I'm getting the same error, but I'm not grouping a regex. What I want to do is find all names/usernames in a lastlog file and return the UNs ONLY.

我有什么:

    s/^[a-z]+ |^[a-z]+[0-9]+/\1/p

我已经看到许多解决方案展示了如何在 awk 中执行此操作,这对于将来参考非常有用,但我想使用 sed 来执行此操作.

I've seen many solutions that show how to do it in awk, which is great for future reference, but I want to do it using sed.

编辑例如输入:

    dzhu             pts/15   n0000d174.cs.uts Wed Feb 17 08:31:22 -0600 2016
    krobbins                                   **Never logged in**
    js24                                       **Never logged in**

推荐答案

如果在替换命令的第一部分中没有任何捕获组,则不能使用反向引用(例如 \1).

You cannot use backreferences (such as \1) if you do not have any capture groups in the first part of your substitution command.

假设您想要该行中的第一个单词,您可以运行以下命令:

Assuming you want the first word in the line, here's a command you can run:

sed -n 's/^\s*\(\w\+\)\s\?.*/\1/p'

说明:

  • -n 抑制 sed 的默认行为以打印它处理的每一行
  • ^\s* 匹配行首后跟任意数量的空格
  • \(\w\+\) 捕获一个或多个单词字符(字母和数字)
  • \s\?.* 匹配一个或零个空格,后跟任意数量的字符.这是为了确保我们匹配捕获组中的整个单词
  • \1 用捕获的组替换匹配的行
  • p 标志打印与表达式匹配的行.结合 -n,这意味着只打印出匹配项.
  • -n suppresses the default behavior of sed to print each line it processes
  • ^\s* matches the start of the line followed by any number of whitespace
  • \(\w\+\) captures one or more word characters (letters and numbers)
  • \s\?.* matches one or zero spaces, followed by any number of characters. This is to make sure we match the whole word in the capture group
  • \1 replaces the matched line with the captured group
  • The p flag prints lines that matched the expression. Combined with -n, this means only matches get printed out.

我希望这会有所帮助!

这篇关于尝试打印匹配表达式时使用 sed 的无效引用 \1的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆