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

5.8k views Asked by At

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

There are 1 answers

2
alexbclay On BEST ANSWER

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!