Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to extract last part of string in bash?

Tags:

string

bash

awk

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?

like image 345
user710818 Avatar asked Sep 14 '12 14:09

user710818


People also ask

How do I get the last 4 characters 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.

How do I get the last word of a string in Linux?

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.

How do you trim the last character in bash?

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.


2 Answers

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.

like image 136
gammay Avatar answered Oct 15 '22 23:10

gammay


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.)

like image 38
ruakh Avatar answered Oct 15 '22 23:10

ruakh