Skip to content
Advertisement

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

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:

example, line, file

i intent with “awk” but the problem is that the words are in different space

Advertisement

Answer

Try

$ awk 'NF>1{print $NF}' file
example.
line.
file.

To get the result in one line as in your example, try:

{
    sub(/./, ",", $NF)
    str = str$NF
}
END { print str }

output:

$ awk -f script.awk file
example, line, file, 

Pure bash:

$ while read line; do [ -z "$line" ] && continue ;echo ${line##* }; done < file
example.
line.
file.
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement