How to extract last part of string in bash?

后端 未结 6 1545
谎友^
谎友^ 2020-12-28 12:39

I have this variable:

A="Some variable has value abc.123"

I need to extract this value i.e abc.123. Is this possible i

6条回答
  •  清歌不尽
    2020-12-28 13:10

    Simplest is

    echo $A | awk '{print $NF}'
    

    Edit: explanation of how this works...

    awk breaks the input into different fields, using whitespace as the separator by default. Hardcoding 5 in place of NF prints out the 5th field in the input:

    echo $A | awk '{print $5}'
    

    NF is a built-in awk variable that gives the total number of fields in the current record. The following returns the number 5 because there are 5 fields in the string "Some variable has value abc.123":

    echo $A | awk '{print NF}'
    

    Combining $ with NF outputs the last field in the string, no matter how many fields your string contains.

提交回复
热议问题