LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Linux - Newbie (https://www.linuxquestions.org/questions/linux-newbie-8/)
-   -   return part of a string in bash (https://www.linuxquestions.org/questions/linux-newbie-8/return-part-of-a-string-in-bash-869844/)

xeon123 03-20-2011 05:03 PM

return part of a string in bash
 
Hi,

I would like to return the last part of a string in an array of strings in bash.

The array contains in each position the content below:
Code:

a.b.c
a.d.f
a
a.d
a.b.c.h

and I would like to return only the last part of each string.
The correct result would be:

Code:

c
f
a
d
h

How can I do that in bash?

Robhogg 03-20-2011 05:29 PM

This could be achieved using Bash's built-in Parameter Expansion feature:

Quote:

${parameter#word}
${parameter##word}
The word is expanded to produce a pattern just as in filename expansion (see Filename Expansion). If the pattern matches the beginning of the expanded value of parameter, then the result of the expansion is the expanded value of parameter with the shortest matching pattern (the ‘#’ case) or the longest matching pattern (the ‘##’ case) deleted. If parameter is ‘@’ or ‘*’, the pattern removal operation is applied to each positional parameter in turn, and the expansion is the resultant list. If parameter is an array variable subscripted with ‘@’ or ‘*’, the pattern removal operation is applied to each member of the array in turn, and the expansion is the resultant list.
Hope this helps,
Rob

kurumi 03-20-2011 07:47 PM

Code:

$ ruby -F"\." -ane 'puts $F[-1]' file
c
f
a
d
h


anishkumarv 03-20-2011 08:14 PM

Hi

In bash

Code:

#!/bin/bash
A=(a.b.c a.d.f a a.d a.b.c.h )
for w in ${A[@]}
do
    echo ${w##*.}
done

In bash using awk:

Code:

#!/bin/bash
A=(a.b.c a.d.f a a.d a.b.c.h )
for w in ${A[@]}
do
    echo $w
done | awk -F. '{print $NF}'


anishkumarv 03-20-2011 08:40 PM

Hi

Try this also

awk -F. '{$0=$NF}1' filename

grail 03-20-2011 09:08 PM

As an addendum to post #4 using bash:
Code:

#!/bin/bash
A=(a.b.c a.d.f a a.d a.b.c.h )
for w in ${A[@]}
do
    echo ${w:(-1)}
    echo ${w##*.}
done

Both will print the last character


All times are GMT -5. The time now is 03:55 PM.