I have this variable:
A="Some variable has value abc.123" I need to extract this value i.e abc.123. Is this possible 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.
with grep : the * means: "match 0 or more instances of the preceding match pattern (which is [^ ] ), and the $ means "match the end of the line." So, this matches the last word after the last space through to the end of the line; ie: abc.
To remove the last n characters of a string, we can use the parameter expansion syntax ${str::-n} in the Bash shell. -n is the number of characters we need to remove from the end of a string.
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.
Yes; this:
A="Some variable has value abc.123" echo "${A##* }" will print this:
abc.123
(The ${parameter##word} notation is explained in §3.5.3 "Shell Parameter Expansion" of the Bash Reference Manual.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With