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?
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.
awk '{ print $NF }' file
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
Using cut 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
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:
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.
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
and man awk
.
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.