Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

linux

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

like image 320
camilo soto Avatar asked May 17 '13 20:05

camilo soto


People also ask

How do I get the last letter of a string in bash?

To access the last n characters of a string, we can use the parameter expansion syntax ${string: -n} in the Bash shell. -n is the number of characters we need to extract from the end of a string.

What is Ctrl Z in bash?

ctrl+z stops the process and returns you to the current shell. You can now type fg to continue process, or type bg to continue the process in the background. Research "bash job control" and see bash manual Job Control Basics.


1 Answers

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. 
like image 120
Fredrik Pihl Avatar answered Sep 21 '22 15:09

Fredrik Pihl