How do I get the last word in each line with bash

前端 未结 6 1383
我在风中等你
我在风中等你 2020-12-07 22:35

For example i have a file:

$ cat file

i am the first example.

i am the second line.

i do a question about a file.

and i need:

         


        
6条回答
  •  悲&欢浪女
    2020-12-07 22:58

    there are many ways. as awk solutions shows, it's the clean solution

    sed solution is to delete anything till the last space. So if there is no space at the end, it should work

    sed 's/.* //g'

    you can avoid sed also and go for a while loop.

    while read line
    do [ -z "$line" ] && continue ;
    echo $line|rev|cut -f1 -d' '|rev
    done < file
    

    it reads a line, reveres it, cuts the first (i.e. last in the original) and restores back

    the same can be done in a pure bash way

    while read line
    do [ -z "$line" ] && continue ;
    echo ${line##* }
    done < file
    

    it is called parameter expansion

提交回复
热议问题