Invalid reference \1 using sed when trying to print matching expression

烂漫一生 提交于 2020-12-16 07:42:27

问题


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.

What I have:

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

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.

Edit for example input:

    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'

Explanation:

  • -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.

I hope this helps!



来源:https://stackoverflow.com/questions/46266517/invalid-reference-1-using-sed-when-trying-to-print-matching-expression

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!