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

前端 未结 6 1385
我在风中等你
我在风中等你 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 23:04

    tldr;

    $ awk '{print $NF}' file.txt | paste -sd, | sed 's/,/, /g'
    

    For a file like this

    $ cat file.txt
    The quick brown fox
    jumps over
    the lazy dog.
    

    the given command will print

    fox, over, dog.
    

    How it works:

    • awk '{print $NF}' : prints the last field of every line
    • paste -sd, : reads stdin serially (-s, one file at a time) and writes fields comma-delimited (-d,)
    • sed 's/,/, /g' : substitutes "," with ", " globally (for all instances)

    References:

    • https://linux.die.net/man/1/awk
    • https://linux.die.net/man/1/paste
    • https://linux.die.net/man/1/sed

提交回复
热议问题