3

I have a file with a format like this:

First Last UID
First Middle Last UID

Basically, some names have middle names (and sometimes more than one middle name). I just want a file that only as UIDs.

Is there a sed or awk command I can run that removes everything before the last space?

2 Answers 2

6

awk

Print the last field of each line using .

The last field is indexed using the NF variable which contains the number of fields for each line. We index it using a dollar sign, the resulting one-liner is easy.

awk '{ print $NF }' file

rs, cat & tail

Another way is to transpose the content of the file, then grab the last line and transpose again (this is fairly easy to see).

The resulting pipe is:

cat file | rs -T | tail -n1 | rs -T

cut & rev

Using and rev we could also achieve this goal by reversing the lines, cutting the first field and then reverse it again.

rev file | cut -d ' ' -f1 | rev

sed

Using we simply remove all chars until a space is found with the ^.* [^ ]*$. This regex means match the beginning of the line ^, followed by any sequence of chars .* and a space . The rest is a sequence of non spaces [^ ]* until the end of the line $. The sed one-liner is:

sed 's/^.* \([^ ]*\)$/\1/' file

Where we capture the last part (in between \( and \)) and sub it back in for the entire line. \1 means the first group caught, which is the last field.

Notes

  1. As Ed Norton cleverly pointed out we could simply not catch the group and remove the former part of the regex. This can be as easily achieved as

    sed 's/.* //' file

    Which is remarkably less complicated and more elegant.

  2. For more information see man sed and man awk.

2
  • 2
    In sed all you'd need is sed 's/.* //'.
    – Ed Morton
    Jun 25, 2015 at 23:23
  • 1
    Yes of course, thanks for the input, should have seen that.
    – ShellFish
    Jun 25, 2015 at 23:28
1

Using grep:

$ grep -o '[^[:blank:]]*$'  file
UID
UID

-o tells grep to print only the matching part. The regex [^[:blank:]]*$ matches the last word on the line.

1
  • Yes grep, great solution!
    – ShellFish
    Jun 25, 2015 at 23:29

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.