简体   繁体   中英

bash, text file remove all text in each line before the last space

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 .

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 .

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM