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?
awk
Print the last field of each line using awk.
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.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:
cut & rev
Using cut and
rev
we could also achieve this goal by reversing the lines, cutting the first field and then reverse it again.sed
Using sed we simply remove all chars until a space is found with the regex
^.* [^ ]*$
. 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: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
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.
For more information see
man sed
andman awk
.